301 lines
15 KiB
Python
301 lines
15 KiB
Python
from pathlib import Path
|
|
import threading
|
|
import pytest
|
|
from pypdf import PdfWriter
|
|
from mentor_pdf_export.models import ExportOptions
|
|
from mentor_pdf_export.scanner import read_project
|
|
from mentor_pdf_export.validation import validate_pdf
|
|
from mentor_pdf_export.exporter import Exporter, output_path
|
|
|
|
|
|
def pdf(path):
|
|
writer = PdfWriter()
|
|
writer.add_blank_page(width=500, height=400)
|
|
with Path(path).open("wb") as f:
|
|
writer.write(f)
|
|
|
|
|
|
def fake_runner(args, cwd, log_dir, cancel, timeout, on_event=None):
|
|
pdf(args[args.index("-a") + 1])
|
|
return 0
|
|
|
|
|
|
def test_validate_pdf(tmp_path):
|
|
file = tmp_path / "a.pdf"; pdf(file)
|
|
assert validate_pdf(file).pages == 1
|
|
file.write_bytes(b"not a pdf")
|
|
with pytest.raises(ValueError):
|
|
validate_pdf(file)
|
|
|
|
|
|
def test_invalid_zero_page_pdf(tmp_path):
|
|
file = tmp_path / "empty.pdf"
|
|
with file.open("wb") as f:
|
|
PdfWriter().write(f)
|
|
with pytest.raises(ValueError, match="页"):
|
|
validate_pdf(file)
|
|
|
|
|
|
def test_success_and_json_report(project_factory, tmp_path):
|
|
info = read_project(project_factory())
|
|
exporter = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner)
|
|
result = exporter.export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
|
|
assert result.status == "success" and result.pages == 1
|
|
assert Path(result.output).is_file()
|
|
assert (Path(result.run_dir) / "result.json").is_file()
|
|
|
|
|
|
def test_old_output_preserved_on_failed_export(project_factory, tmp_path):
|
|
info = read_project(project_factory())
|
|
output = output_path(info, tmp_path / "pdfs"); output.parent.mkdir(); output.write_bytes(b"previous")
|
|
def failure(*args):
|
|
return 2
|
|
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=failure).export(info, output.parent, ExportOptions(overwrite=True), threading.Event())
|
|
assert result.status == "failed"
|
|
assert output.read_bytes() == b"previous"
|
|
|
|
|
|
def test_existing_output_needs_explicit_overwrite(project_factory, tmp_path):
|
|
info = read_project(project_factory())
|
|
output = output_path(info, tmp_path / "pdfs"); output.parent.mkdir(); output.write_bytes(b"previous")
|
|
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner).export(info, output.parent, ExportOptions(), threading.Event())
|
|
assert result.status == "skipped"
|
|
assert output.read_bytes() == b"previous"
|
|
|
|
|
|
def test_failure_not_published_even_when_file_exists(project_factory, tmp_path):
|
|
info = read_project(project_factory())
|
|
def bad(args, *rest):
|
|
pdf(args[args.index("-a") + 1]); return 9
|
|
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=bad).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
|
|
assert result.status == "failed"
|
|
assert not output_path(info, tmp_path / "pdfs").exists()
|
|
|
|
|
|
def test_source_change_never_claims_success(project_factory, tmp_path):
|
|
project = project_factory(); info = read_project(project)
|
|
def changing(args, *rest):
|
|
pdf(args[args.index("-a") + 1])
|
|
project.write_bytes(project.read_bytes() + b"\nKEY ExternalEdit 1\n")
|
|
return 0
|
|
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=changing).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
|
|
assert result.status == "uncertain"
|
|
assert not output_path(info, tmp_path / "pdfs").exists()
|
|
|
|
|
|
def test_duplicate_project_names_have_distinct_outputs(project_factory, tmp_path):
|
|
a = read_project(project_factory("a", "same")); b = read_project(project_factory("b", "same"))
|
|
from mentor_pdf_export.naming import plan_output_directories
|
|
directories=plan_output_directories([a,b],tmp_path/"out",tmp_path/"runs")
|
|
assert output_path(a,directories[0]) != output_path(b,directories[1])
|
|
assert output_path(a,directories[0]).name == output_path(b,directories[1]).name == "same.pdf"
|
|
|
|
|
|
def test_cannot_output_inside_source(project_factory, tmp_path):
|
|
info = read_project(project_factory())
|
|
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner).export(info, info.path.parent / "pdf", ExportOptions(), threading.Event())
|
|
assert result.status == "failed"
|
|
|
|
|
|
def test_pre_cancel_returns_cancelled(project_factory, tmp_path):
|
|
info = read_project(project_factory())
|
|
cancel = threading.Event(); cancel.set()
|
|
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner).export(info, tmp_path / "pdfs", ExportOptions(), cancel)
|
|
assert result.status == "cancelled"
|
|
|
|
|
|
def test_final_source_check_is_before_publish(project_factory,tmp_path,monkeypatch):
|
|
import mentor_pdf_export.exporter as module
|
|
info=read_project(project_factory())
|
|
output=output_path(info,tmp_path/"pdfs");output.parent.mkdir();output.write_bytes(b"previous")
|
|
original=module.fingerprint
|
|
count=0
|
|
def checked(*args):
|
|
nonlocal count
|
|
count+=1
|
|
assert output.read_bytes()==b"previous", "final source validation happened after publication"
|
|
return original(*args)
|
|
monkeypatch.setattr(module,"fingerprint",checked)
|
|
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True),threading.Event())
|
|
assert result.status=="success"
|
|
|
|
|
|
def test_result_record_failure_never_overwrites_old_pdf(project_factory,tmp_path,monkeypatch):
|
|
import mentor_pdf_export.exporter as module
|
|
info=read_project(project_factory())
|
|
output=output_path(info,tmp_path/"pdfs");output.parent.mkdir();output.write_bytes(b"previous")
|
|
original=module.write_json
|
|
def fail_result(path,data):
|
|
if Path(path).name=="result.json":raise OSError("disk full")
|
|
return original(path,data)
|
|
monkeypatch.setattr(module,"write_json",fail_result)
|
|
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True),threading.Event())
|
|
assert result.status in {"failed","uncertain"}
|
|
assert output.read_bytes()==b"previous"
|
|
|
|
|
|
def test_post_publish_record_failure_returns_traceable_uncertain_result(project_factory,tmp_path,monkeypatch):
|
|
import mentor_pdf_export.exporter as module
|
|
info=read_project(project_factory())
|
|
original=module.write_json
|
|
count=0
|
|
def fail_final(path,data):
|
|
nonlocal count
|
|
if Path(path).name=="result.json":
|
|
count+=1
|
|
if count>=2:raise OSError("disk full after publish")
|
|
return original(path,data)
|
|
monkeypatch.setattr(module,"write_json",fail_final)
|
|
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,tmp_path/"pdfs",ExportOptions(),threading.Event())
|
|
assert result.status=="uncertain"
|
|
assert Path(result.output).is_file()
|
|
assert (Path(result.run_dir)/"result.json").is_file()
|
|
|
|
|
|
def test_staging_stat_failure_still_returns_and_records_result(project_factory,tmp_path,monkeypatch):
|
|
info=read_project(project_factory())
|
|
original=Path.exists
|
|
def denied(path):
|
|
if path.name.endswith(".partial.pdf"):raise OSError("staging stat denied")
|
|
return original(path)
|
|
monkeypatch.setattr(Path,"exists",denied)
|
|
def failure(args,*rest):
|
|
pdf(args[args.index("-a")+1]);return 2
|
|
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=failure).export(info,tmp_path/"pdfs",ExportOptions(),threading.Event())
|
|
assert result.status=="failed"
|
|
assert (Path(result.run_dir)/"result.json").is_file()
|
|
assert "暂存" in result.message
|
|
|
|
|
|
def test_style_failure_never_replaces_old_output(project_factory,tmp_path,monkeypatch):
|
|
import mentor_pdf_export.exporter as module
|
|
info=read_project(project_factory())
|
|
output=output_path(info,tmp_path/"pdfs");output.parent.mkdir();output.write_bytes(b"previous")
|
|
def broken(*args):raise ValueError("unsupported font glyph")
|
|
monkeypatch.setattr(module,"apply_pdf_style",broken)
|
|
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True,font_mapping="arial"),threading.Event())
|
|
assert result.status=="failed" and output.read_bytes()==b"previous"
|
|
|
|
|
|
def test_direct_export_uses_original_project_without_creating_copy_or_ini(project_factory,tmp_path):
|
|
project=project_factory();info=read_project(project)
|
|
ini=project.parent/'dxpdf.ini';ini.write_bytes(b'Color 2\nFONT_CUSTOM_FONTS Courier-Bold\n')
|
|
before={p.relative_to(project.parent):p.read_bytes() for p in project.parent.rglob('*') if p.is_file()}
|
|
def direct(args,cwd,log_dir,*rest):
|
|
assert Path(args[args.index('-project')+1])==project.resolve()
|
|
assert Path(cwd)==project.parent.resolve()
|
|
assert not (Path(log_dir)/'project').exists()
|
|
return fake_runner(args,cwd,log_dir,*rest)
|
|
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=direct).export(info,tmp_path/'pdfs',ExportOptions(),threading.Event())
|
|
assert result.status=='success',result.message
|
|
assert before=={p.relative_to(project.parent):p.read_bytes() for p in project.parent.rglob('*') if p.is_file()}
|
|
assert not list(Path(result.run_dir).rglob('*.prj'))
|
|
|
|
|
|
def test_overwrite_has_no_previous_pdf_backup(project_factory,tmp_path):
|
|
info=read_project(project_factory());output=output_path(info,tmp_path/'pdfs');output.parent.mkdir();output.write_bytes(b'previous')
|
|
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True),threading.Event())
|
|
assert result.status=='success'
|
|
assert not (Path(result.run_dir)/'previous-output.pdf').exists()
|
|
assert not list(Path(result.run_dir).rglob('*.pdf'))
|
|
|
|
|
|
def test_failed_export_does_not_keep_unpublished_pdf_copy(project_factory,tmp_path):
|
|
info=read_project(project_factory())
|
|
def failed(args,*rest):pdf(args[args.index('-a')+1]);return 7
|
|
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=failed).export(info,tmp_path/'pdfs',ExportOptions(),threading.Event())
|
|
assert result.status=='failed'
|
|
assert not list(Path(result.run_dir).rglob('*.pdf'))
|
|
assert not list((tmp_path/'pdfs').glob('*.partial.pdf'))
|
|
|
|
|
|
def test_direct_mode_rejects_library_override_without_touching_original(project_factory,tmp_path):
|
|
project=project_factory();before=project.read_bytes()
|
|
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=fake_runner).export(read_project(project),tmp_path/'pdfs',ExportOptions(library_override=str(tmp_path/'library.lmc')),threading.Event())
|
|
assert result.status=='failed' and '依赖库' in result.message
|
|
assert project.read_bytes()==before
|
|
assert not (tmp_path/'runs').exists()
|
|
|
|
|
|
@pytest.mark.parametrize("native_rc", [0, 9])
|
|
def test_source_change_explains_files_and_records_diff_without_publication(project_factory, tmp_path, native_rc):
|
|
import json
|
|
project = project_factory()
|
|
info = read_project(project)
|
|
old = project.parent / "database" / "obsolete.txt"
|
|
old.write_bytes(b"old native record")
|
|
output = output_path(info, tmp_path / "pdfs")
|
|
output.parent.mkdir()
|
|
output.write_bytes(b"previous PDF")
|
|
def changing(args, *rest):
|
|
pdf(args[args.index("-a") + 1])
|
|
(project.parent / "database" / "icdb.dat").write_bytes(b"updated by native engine")
|
|
(project.parent / "database" / "new.txt").write_bytes(b"new native record")
|
|
old.unlink()
|
|
return native_rc
|
|
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=changing).export(info, output.parent, ExportOptions(overwrite=True), threading.Event())
|
|
assert result.status == "uncertain" and not result.output
|
|
assert output.read_bytes() == b"previous PDF"
|
|
for detail in ("database/icdb.dat", "新增", "删除", "原生引擎", "source-diff.json"):
|
|
assert detail in result.message
|
|
changes = json.loads((Path(result.run_dir) / "source-diff.json").read_text(encoding="utf-8"))
|
|
assert changes == {"modified": ["database/icdb.dat"], "added": ["database/new.txt"], "removed": ["database/obsolete.txt"]}
|
|
|
|
|
|
@pytest.mark.parametrize('custom_database', ['database', 'DATA'])
|
|
def test_native_database_updates_publish_pdf_with_explicit_warning(project_factory,tmp_path,custom_database):
|
|
import json
|
|
project=project_factory(); info=read_project(project)
|
|
if custom_database!='database':
|
|
(project.parent/'database').rename(project.parent/custom_database)
|
|
project.write_text(project.read_text().replace('database',custom_database))
|
|
def updating(args,*rest):
|
|
pdf(args[args.index('-a')+1])
|
|
(project.parent/custom_database/'icdb.dat').write_bytes(b'native updated database')
|
|
logs=project.parent/custom_database/'cdbsvr'/'log'/'run';logs.mkdir(parents=True)
|
|
(logs/'native.txt').write_bytes(b'native log')
|
|
return 0
|
|
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=updating).export(info,tmp_path/'pdfs',ExportOptions(),threading.Event())
|
|
assert result.status=='success' and result.pages==1 and Path(result.output).is_file()
|
|
assert result.warnings and '只读' in result.message
|
|
commit=json.loads((Path(result.run_dir)/'commit.json').read_text(encoding='utf-8'))
|
|
assert commit['source_verified_before_publish'] is False
|
|
assert commit['source_content_identical'] is False
|
|
assert commit['source_change_policy']=='native_updates_warn'
|
|
assert not commit['backup_created'] and not commit['working_copy_created']
|
|
assessment=json.loads((Path(result.run_dir)/'source-assessment.json').read_text(encoding='utf-8'))
|
|
assert not any(assessment['blocked_changes'].values())
|
|
assert assessment['native_updates']['modified']==[custom_database+'/icdb.dat']
|
|
|
|
|
|
def test_strict_source_mode_still_blocks_native_database_update(project_factory,tmp_path):
|
|
project=project_factory();info=read_project(project)
|
|
def updating(args,*rest):
|
|
pdf(args[args.index('-a')+1]);(project.parent/'database/icdb.dat').write_bytes(b'native update');return 0
|
|
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=updating).export(info,tmp_path/'pdfs',ExportOptions(strict_source=True),threading.Event())
|
|
assert result.status=='uncertain' and not result.output
|
|
assert not output_path(info,tmp_path/'pdfs').exists()
|
|
|
|
|
|
@pytest.mark.parametrize('outcome', ['failed','cancelled','timeout'])
|
|
def test_native_updates_do_not_hide_real_failures_or_cancellation(project_factory,tmp_path,outcome):
|
|
project=project_factory();info=read_project(project)
|
|
target=output_path(info,tmp_path/'pdfs');target.parent.mkdir();target.write_bytes(b'previous')
|
|
def updating(args,*rest):
|
|
pdf(args[args.index('-a')+1]);(project.parent/'database/icdb.dat').write_bytes(b'native update')
|
|
if outcome=='cancelled':raise InterruptedError('stop requested')
|
|
if outcome=='timeout':raise TimeoutError('timeout')
|
|
return 9
|
|
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=updating).export(info,target.parent,ExportOptions(overwrite=True),threading.Event())
|
|
assert result.status==outcome and not result.output and result.warnings
|
|
assert target.read_bytes()==b'previous'
|
|
|
|
|
|
def test_invalid_pdf_is_not_published_even_when_changes_are_native(project_factory,tmp_path):
|
|
project=project_factory();info=read_project(project)
|
|
def invalid(args,*rest):
|
|
Path(args[args.index('-a')+1]).write_bytes(b'not a PDF')
|
|
(project.parent/'database/icdb.dat').write_bytes(b'native update');return 0
|
|
result=Exporter(Path('fake.exe'),tmp_path/'runs',runner=invalid).export(info,tmp_path/'pdfs',ExportOptions(),threading.Event())
|
|
assert result.status=='failed' and not result.output
|