release: ship validated Mentor PDF exporter v1.0.0

This commit is contained in:
阿白叔 committed 2026-10-10 16:28:18 +08:00
1 parent d4928af5b6
commit 0334f2b85b
50 files changed
+3998 -219

No files matched your search

+63 -3
View File
@@ -1,4 +1,5 @@
import json
import pytest
from pathlib import Path
from mentor_pdf_export.cli import main
@@ -7,7 +8,8 @@ def test_self_check_writes_machine_readable_report(tmp_path):
report=tmp_path / "check.json"
assert main(["--self-check","--report",str(report)]) == 0
data=json.loads(report.read_text(encoding="utf-8"))
assert data["version"] == "0.1.0"
from mentor_pdf_export import __version__
assert data["version"] == __version__
assert "engine_available" in data
@@ -29,7 +31,7 @@ def test_report_inside_source_is_rejected_before_export(project_factory,tmp_path
project=project_factory()
protected=project.parent/"settings.json";protected.write_text("original")
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
def runner(args,*rest):
def runner(args,*rest,env=None):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out)
return 0
@@ -48,7 +50,7 @@ def test_queue_destinations_protect_every_source_before_first_export(project_fac
a=project_factory("a");b=project_factory("b")
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
before=fingerprint(b.parent)
def runner(args,*rest):
def runner(args,*rest,env=None):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out)
return 0
@@ -70,3 +72,61 @@ def test_self_check_can_refresh_its_own_report(tmp_path):
report=tmp_path/"self-check.json"
assert main(["--self-check","--report",str(report)]) == 0
assert main(["--self-check","--report",str(report)]) == 0
def test_cli_accepts_explicit_print_and_font_profiles(tmp_path):
report=tmp_path/"style-check.json"
assert main(["--self-check","--font-mapping","arial","--print-theme","high_contrast","--report",str(report)])==0
def test_cli_rejects_library_replacement_in_direct_mode(tmp_path):
assert main(["--self-check","--library",str(tmp_path/"matching.lmc")])==2
@pytest.mark.parametrize('strict',[False,True])
def test_cli_native_update_warning_exit_and_strict_fallback(project_factory,tmp_path,monkeypatch,strict):
from mentor_pdf_export import cli
from mentor_pdf_export.exporter import Exporter
from pypdf import PdfWriter
project=project_factory();engine=tmp_path/'sch2pdf.exe';engine.write_bytes(b'fake')
def runner(args,*rest,env=None):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as out:writer.write(out)
(project.parent/'database/icdb.dat').write_bytes(b'native update');return 0
monkeypatch.setattr(cli,'Exporter',lambda engine,runs:Exporter(engine,runs,runner=runner))
report=tmp_path/'report.json'
args=['--export',str(project),'--engine',str(engine),'--output',str(tmp_path/'pdfs'),'--runs-root',str(tmp_path/'runs'),'--report',str(report)]
if strict:args.append('--strict-source')
assert main(args)==(1 if strict else 0)
result=json.loads(report.read_text(encoding='utf-8'))['results'][0]
assert result['status']==('uncertain' if strict else 'success')
if not strict:assert result['warnings'] and Path(result['output']).is_file()
def test_cli_strict_source_flag_reaches_ui(qtbot,tmp_path,monkeypatch):
from mentor_pdf_export import ui
original=ui.MainWindow;windows=[]
def capture(*args,**kwargs):
window=original(*args,**kwargs);qtbot.addWidget(window);windows.append(window);return window
monkeypatch.setattr(ui,'MainWindow',capture)
assert main(['--strict-source','--ui-smoke',str(tmp_path/'ui.png')])==0
assert windows[0].strict_source_check.isChecked()
@pytest.mark.parametrize('flags,exit_code',[
(['--font-mapping','preserve'],0),
(['--font-mapping','preserve','--no-legacy-gbk'],0),
(['--font-mapping','preserve','--legacy-gbk'],2),
])
def test_cli_preserve_normalizes_implicit_not_explicit_gbk(project_factory,tmp_path,monkeypatch,flags,exit_code):
from mentor_pdf_export import cli
from mentor_pdf_export.exporter import Exporter
from pypdf import PdfWriter
project=project_factory();engine=tmp_path/'sch2pdf.exe';engine.write_bytes(b'fake')
def runner(args,*rest,env=None):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as out:writer.write(out)
return 0
monkeypatch.setattr(cli,'Exporter',lambda e,r:Exporter(e,r,runner=runner))
rc=main(['--export',str(project),'--engine',str(engine),'--output',str(tmp_path/'out'),'--runs-root',str(tmp_path/'runs'),*flags])
assert rc==exit_code
+39
View File
@@ -323,3 +323,42 @@ def test_callback_error_stops_owned_tree_but_not_other_process(tmp_path, monkeyp
if other.poll() is None:
other.kill()
other.wait(timeout=10)
def test_success_does_not_kill_background_database_flush(tmp_path,owned_process_handles):
import subprocess
import win32event
marker=tmp_path/'flush-complete.txt';pid_file=tmp_path/'flush.pid'
child=f"import time,pathlib;time.sleep(.6);pathlib.Path({str(marker)!r}).write_text('flushed')"
parent=("import subprocess,pathlib;"
f"p=subprocess.Popen([{sys.executable!r},'-B','-c',{child!r}],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);"
f"pathlib.Path({str(pid_file)!r}).write_text(str(p.pid))")
children=[]
def started(message):
if 'PID=' in message:children.append(capture_child(pid_file,owned_process_handles))
assert run_engine([sys.executable,'-B','-c',parent],tmp_path,tmp_path/'logs',threading.Event(),10,started)==0
assert win32event.WaitForSingleObject(children[0],5000)==win32event.WAIT_OBJECT_0
assert marker.read_text()=='flushed'
def test_cancel_after_parent_success_does_not_abort_completed_native_writeback(tmp_path,monkeypatch,owned_process_handles):
import win32event
from mentor_pdf_export import engine
marker=tmp_path/'flush-late-stop.txt';pid_file=tmp_path/'late-stop.pid'
child=f"import time,pathlib;time.sleep(.6);pathlib.Path({str(marker)!r}).write_text('flushed')"
parent=("import subprocess,pathlib;"
f"p=subprocess.Popen([{sys.executable!r},'-B','-c',{child!r}],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);"
f"pathlib.Path({str(pid_file)!r}).write_text(str(p.pid))")
children=[];parents=[];original=engine._create_job;cancel=threading.Event()
def bind(process):
parents.append(owned_process_handles(process.pid));return original(process)
def started(message):
if 'PID=' in message:
children.append(capture_child(pid_file,owned_process_handles))
assert win32event.WaitForSingleObject(parents[0],5000)==win32event.WAIT_OBJECT_0
cancel.set()
monkeypatch.setattr(engine,'_create_job',bind)
with pytest.raises(InterruptedError):
run_engine([sys.executable,'-B','-c',parent],tmp_path,tmp_path/'logs',cancel,10,started)
assert win32event.WaitForSingleObject(children[0],5000)==win32event.WAIT_OBJECT_0
assert marker.read_text()=='flushed'
+138 -2
View File
@@ -76,7 +76,7 @@ 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.parent / "database/icdb.dat").write_bytes(b"edited elsewhere")
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"
@@ -85,7 +85,10 @@ def test_source_change_never_claims_success(project_factory, tmp_path):
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"))
assert output_path(a, tmp_path / "out") != output_path(b, tmp_path / "out")
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):
@@ -162,3 +165,136 @@ def test_staging_stat_failure_still_returns_and_records_result(project_factory,t
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
+72
View File
@@ -0,0 +1,72 @@
import threading
from pathlib import Path
from pypdf import PdfWriter
from mentor_pdf_export.exporter import Exporter,output_path
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.scanner import read_project
from mentor_pdf_export.workers import BatchWorker
def test_pdf_uses_original_project_basename_without_hash(project_factory,tmp_path):
project=read_project(project_factory('input','音频_Test'))
assert output_path(project,tmp_path/'out').name=='音频_Test.pdf'
def test_duplicate_names_export_to_natural_subfolders_without_overwrite(qapp,project_factory,tmp_path):
a=read_project(project_factory('design/Work','same'))
b=read_project(project_factory('design/Cert','same'))
def runner(args,*rest):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as f:writer.write(f)
return 0
worker=BatchWorker([(0,a),(1,b)],tmp_path/'out',ExportOptions(overwrite=True),Exporter(Path('fake.exe'),tmp_path/'runs',runner=runner))
worker.run()
assert [r.status for r in worker.results]==['success','success']
assert [Path(r.output).relative_to(tmp_path/'out').as_posix() for r in worker.results]==['Work/same.pdf','Cert/same.pdf']
def test_unique_names_keep_flat_output(qapp,project_factory,tmp_path):
from mentor_pdf_export.naming import plan_output_directories
a=read_project(project_factory('a','One'));b=read_project(project_factory('b','Two'))
assert plan_output_directories([a,b],tmp_path/'out',tmp_path/'runs')==[tmp_path/'out',tmp_path/'out']
def test_derived_subfolder_cannot_enter_any_source_before_first_native_call(qapp,project_factory,tmp_path):
a=read_project(project_factory('design/root/Work','same'))
b=read_project(project_factory('design/root/Cert','same'))
# root is an allowed ancestor, but derived Work/Cert outputs would hit sources.
calls=[]
worker=BatchWorker([(0,a),(1,b)],tmp_path/'design/root',ExportOptions(),Exporter(Path('fake.exe'),tmp_path/'runs',runner=lambda *args:calls.append(args)))
worker.run()
assert not calls and not worker.results
def test_retry_subset_preserves_collision_folders(qapp,project_factory,tmp_path):
a=read_project(project_factory('design/Work','same'));b=read_project(project_factory('design/Cert','same'))
def runner(args,*rest):
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as f:writer.write(f)
return 0
worker=BatchWorker([(0,a)],tmp_path/'out',ExportOptions(),Exporter(Path('fake.exe'),tmp_path/'runs',runner=runner),all_projects=[a,b])
worker.run()
assert Path(worker.results[0].output).relative_to(tmp_path/'out').as_posix()=='Work/same.pdf'
def test_junction_aliases_cannot_merge_same_name_outputs(qapp,project_factory,tmp_path):
import os,pytest
if os.name!='nt':pytest.skip('Windows junction regression')
import _winapi
a=read_project(project_factory('design/Work','same'));b=read_project(project_factory('design/Cert','same'))
output=tmp_path/'out';output.mkdir();shared=tmp_path/'shared';shared.mkdir()
_winapi.CreateJunction(str(shared),str(output/'Work'))
_winapi.CreateJunction(str(shared),str(output/'Cert'))
assert (output/'Work').resolve()==(output/'Cert').resolve()==shared
calls=[]
def runner(args,*rest):
calls.append(args);writer=PdfWriter();writer.add_blank_page(width=500,height=400)
with Path(args[args.index('-a')+1]).open('wb') as f:writer.write(f)
return 0
worker=BatchWorker([(0,a),(1,b)],output,ExportOptions(overwrite=True),Exporter(Path('fake.exe'),tmp_path/'runs',runner=runner))
worker.run()
assert not calls and not worker.results
assert not (shared/'same.pdf').exists()
+330
View File
@@ -0,0 +1,330 @@
from pathlib import Path
import threading
import pytest
from pypdf import PdfReader, PdfWriter
from pypdf.generic import (DictionaryObject,NameObject,NumberObject,ArrayObject,FloatObject,TextStringObject,ByteStringObject,DecodedStreamObject,ContentStream)
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.pdf_styles import apply_pdf_style, decode_legacy_text, contrast_rgb
def legacy_pdf(path,text="注意事项 输入网络 Ω μ ± ×"):
writer=PdfWriter();page=writer.add_blank_page(width=640,height=220)
font=DictionaryObject({NameObject("/Type"):NameObject("/Font"),NameObject("/Subtype"):NameObject("/Type1"),NameObject("/BaseFont"):NameObject("/Courier-Bold"),NameObject("/Encoding"):NameObject("/WinAnsiEncoding")})
page[NameObject("/Resources")]=DictionaryObject({NameObject("/Font"):DictionaryObject({NameObject("/F1"):writer._add_object(font)})})
stream=ContentStream(None,writer)
stream.operations=[
([FloatObject(1),FloatObject(1),FloatObject(1)],b"rg"),
([NumberObject(0),NumberObject(0),NumberObject(640),NumberObject(220)],b"re"),([],b"f"),
([FloatObject(0),FloatObject(1),FloatObject(1)],b"RG"),
([NumberObject(20),NumberObject(25)],b"m"),([NumberObject(600),NumberObject(25)],b"l"),([],b"S"),
([FloatObject(1),FloatObject(1),FloatObject(0)],b"rg"),
([],b"BT"),([NameObject("/F1"),NumberObject(14)],b"Tf"),
([NumberObject(1),NumberObject(0),NumberObject(0),NumberObject(1),NumberObject(20),NumberObject(120)],b"Tm"),
([ByteStringObject(text.encode("gbk"))],b"Tj"),([],b"ET"),
]
page[NameObject("/Contents")]=writer._add_object(stream)
annotation=DictionaryObject({NameObject("/Type"):NameObject("/Annot"),NameObject("/Subtype"):NameObject("/Link"),NameObject("/Rect"):ArrayObject([NumberObject(10),NumberObject(10),NumberObject(30),NumberObject(20)]),NameObject("/A"):DictionaryObject({NameObject("/S"):NameObject("/URI"),NameObject("/URI"):TextStringObject("https://example.invalid")})})
page[NameObject("/Annots")]=ArrayObject([writer._add_object(annotation)])
writer.add_outline_item("Power",0)
with Path(path).open("wb") as out:writer.write(out)
def test_legacy_gbk_bytes_decode_without_guessing_ascii():
text="注意事项 Ω μ ± ×"
assert decode_legacy_text(text.encode("gbk"), legacy_gbk=True)==(text,True)
assert decode_legacy_text(b"R1 10K")==("R1 10K",False)
def test_palette_preserves_white_and_darkens_cyan_and_yellow():
assert contrast_rgb((1,1,1),text=True)==(1,1,1)
assert max(contrast_rgb((1,1,0),text=True))<.4
cyan=contrast_rgb((0,1,1),text=True)
assert max(cyan)<.5
tinted=contrast_rgb((0,1,0),text=False)
assert min(tinted)>.8
def test_original_mode_does_not_touch_bytes(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file);before=file.read_bytes()
report=apply_pdf_style(file,ExportOptions())
assert file.read_bytes()==before and not report.modified
def test_high_contrast_preserves_vectors_page_box_annotations_outline(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
before=PdfReader(file);box=list(before.pages[0].mediabox)
report=apply_pdf_style(file,ExportOptions(print_theme="high_contrast"))
after=PdfReader(file)
assert report.modified and report.color_ops>0
assert list(after.pages[0].mediabox)==box
assert after.outline[0].title=="Power"
assert after.pages[0]['/Annots'][0].get_object()['/A']['/URI']=="https://example.invalid"
operators=[op for _,op in ContentStream(after.pages[0].get_contents(),after).operations]
assert b"m" in operators and b"l" in operators and b"S" in operators
assert len(after.pages[0].get('/Resources',{}).get('/XObject',{}))==0
def test_arial_with_cjk_fallback_recovers_real_chinese(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
report=apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
reader=PdfReader(file,strict=True);text=reader.pages[0].extract_text()
assert "注意事项" in text and "输入网络" in text
assert "Ω" in text and "μ" in text and "±" in text and "×" in text
assert report.repaired_strings==1 and report.fallback_strings==1
assert reader.outline[0].title=="Power"
assert reader.pages[0]['/Annots'][0].get_object()['/A']['/URI']=="https://example.invalid"
def test_pre_cancel_never_modifies_pdf(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file);before=file.read_bytes()
cancel=threading.Event();cancel.set()
with pytest.raises(InterruptedError):
apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True),cancel)
assert file.read_bytes()==before
def test_normal_western_accent_is_not_guessed_as_chinese():
assert decode_legacy_text("école".encode("cp1252"))==("école",False)
def test_compound_text_requires_explicit_support_not_silent_success(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
page=w.pages[0];stream=ContentStream(page.get_contents(),w)
stream.operations=[([ArrayObject([operands[0]])],b'TJ') if op==b'Tj' else (operands,op) for operands,op in stream.operations]
page[NameObject('/Contents')]=w._add_object(stream)
with file.open('wb') as out:w.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match="TJ"):
apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
assert file.read_bytes()==before
def test_nonprinting_native_control_does_not_require_missing_font_glyph(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file,"A\r注意事项")
report=apply_pdf_style(file,ExportOptions(font_mapping="arial",legacy_gbk=True))
assert "注意事项" in PdfReader(file).pages[0].extract_text()
assert report.repaired_strings==1
def test_high_contrast_sets_readable_minimum_stroke_without_moving_path(tmp_path):
file=tmp_path/"native.pdf";legacy_pdf(file)
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
page=w.pages[0];stream=ContentStream(page.get_contents(),w)
stream.operations.insert(0,([FloatObject(.01)],b'w'))
page[NameObject('/Contents')]=w._add_object(stream)
with file.open('wb') as out:w.write(out)
apply_pdf_style(file,ExportOptions(print_theme="high_contrast"))
after=PdfReader(file);ops=ContentStream(after.pages[0].get_contents(),after).operations
widths=[float(a[0]) for a,o in ops if o==b'w']
assert widths and min(widths)>=.35
assert ([NumberObject(20),NumberObject(25)],b'm') in ops
assert ([NumberObject(600),NumberObject(25)],b'l') in ops
def rewrite_operations(file, transform):
reader=PdfReader(file); writer=PdfWriter(); writer.clone_document_from_reader(reader)
page=writer.pages[0]; stream=ContentStream(page.get_contents(),writer)
stream.operations=transform(stream.operations)
page[NameObject('/Contents')]=writer._add_object(stream)
with file.open('wb') as output: writer.write(output)
@pytest.mark.parametrize("raw,text",[(b"\xb1\xd7","±×"),(b"\xb5\xb1","µ±"),(b"\xc9\xc9","ÉÉ")])
def test_declared_winansi_never_guessed_as_gbk(raw,text):
assert decode_legacy_text(raw)==(text,False)
def test_gbk_repair_requires_explicit_font_mapping():
with pytest.raises(ValueError,match="字体"):
ExportOptions(legacy_gbk=True)
@pytest.mark.parametrize("color,operator",[([0],b'g'),([0,0,0,1],b'k')])
def test_high_contrast_tracks_gray_and_cmyk_text_after_white_fill(tmp_path,color,operator):
file=tmp_path/'native.pdf'; legacy_pdf(file,'LABEL')
rewrite_operations(file,lambda ops: [([NumberObject(v) for v in color],operator) if o==b'rg' and a==[1,1,0] else (a,o) for a,o in ops])
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file); ops=ContentStream(r.pages[0].get_contents(),r).operations
begin=next(i for i,(_,o) in enumerate(ops) if o==b'BT')
assert ops[begin+1][1]==b'rg'
assert max(float(v) for v in ops[begin+1][0])<.4
@pytest.mark.parametrize("operator",[b'Tc',b'Tw'])
def test_nonzero_text_spacing_fails_before_staging_replacement(tmp_path,operator):
file=tmp_path/'native.pdf'; legacy_pdf(file,'A A')
rewrite_operations(file,lambda ops: [(a,o) for a,o in ops] + [])
rewrite_operations(file,lambda ops: [(a,o) for a,o in ops[:1]]+[( [NumberObject(5)],operator)]+ops[1:])
before=file.read_bytes()
with pytest.raises(ValueError,match='间距'):
apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert file.read_bytes()==before
def test_tinted_palette_is_idempotent():
color=contrast_rgb((0,1,1),text=False)
assert contrast_rgb(color,text=False)==color
def test_font_mapping_keeps_declared_winansi_symbols(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'ASCII')
raw='±× µ±'.encode('cp1252')
rewrite_operations(file,lambda ops:[([ByteStringObject(raw)],o) if o==b'Tj' else (a,o) for a,o in ops])
report=apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert '±× µ±' in PdfReader(file).pages[0].extract_text()
assert report.repaired_strings==0
def test_unknown_original_font_advance_fails_safe(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
r=PdfReader(file);w=PdfWriter();w.clone_document_from_reader(r)
w.pages[0]['/Resources']['/Font']['/F1'].get_object()[NameObject('/BaseFont')]=NameObject('/UnknownNoMetrics')
with file.open('wb') as out:w.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match='字宽'):
apply_pdf_style(file,ExportOptions(font_mapping='arial'))
assert file.read_bytes()==before
def test_explicit_gbk_retains_standalone_declared_winansi_symbol():
assert decode_legacy_text(b"\xa3",legacy_gbk=True)==("£",False)
@pytest.mark.parametrize('width,height,panel',[(.2,12,False),(70,40,True)])
def test_high_contrast_distinguishes_stroke_glyph_fills_from_panels(tmp_path,width,height,panel):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
path_ops=[([NumberObject(0),NumberObject(1),NumberObject(1)],b'rg'),([NumberObject(30),NumberObject(40),FloatObject(width),FloatObject(height)],b're'),([],b'f')]
rewrite_operations(file,lambda ops:path_ops+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);color=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'rg':color=tuple(float(x) for x in args)
if op==b'f':break
assert (min(color)>.8) if panel else (max(color)<.5)
def test_scaled_rectangle_glyph_is_not_mistaken_for_large_panel(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
path_ops=[([FloatObject(.01),NumberObject(0),NumberObject(0),FloatObject(.01),NumberObject(0),NumberObject(0)],b'cm'),([NumberObject(0),NumberObject(1),NumberObject(1)],b'rg'),([NumberObject(30),NumberObject(40),NumberObject(70),NumberObject(400)],b're'),([],b'f')]
rewrite_operations(file,lambda ops:path_ops+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);color=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'rg':color=tuple(float(x) for x in args)
if op==b'f':break
assert max(color)<.5
def test_minimum_stroke_is_in_physical_points_after_scaled_transform(tmp_path):
file=tmp_path/'native.pdf';legacy_pdf(file,'LABEL')
prefix=[([FloatObject(.01),NumberObject(0),NumberObject(0),FloatObject(.01),NumberObject(0),NumberObject(0)],b'cm'),([FloatObject(.1)],b'w')]
rewrite_operations(file,lambda ops:prefix+ops)
apply_pdf_style(file,ExportOptions(print_theme='high_contrast'))
r=PdfReader(file);width=None
for args,op in ContentStream(r.pages[0].get_contents(),r).operations:
if op==b'w':width=float(args[0])
if op==b'S':break
assert width*.01>=.35
@pytest.mark.parametrize("mapping", ["arial", "simsun", "msyh"])
def test_font_only_repair_preserves_reference_colors_widths_and_geometry(tmp_path, mapping):
file = tmp_path / "native.pdf"
legacy_pdf(file)
writer = PdfWriter(clone_from=file)
page = writer.pages[0]
stream = ContentStream(page.get_contents(), writer)
# Explicit hairline, a thicker emphasis stroke, and red/blue/teal/green
# reference colors must survive even when Chinese text is repaired.
additions = [([NumberObject(0)], b"w")]
for color in ((1,0,0), (0,0,1), (0,.5,.5), (0,.5,0), (0,0,.5), (.5,0,.5)):
additions += [([FloatObject(v) for v in color], b"RG"),
([NumberObject(20), NumberObject(50)], b"m"),
([NumberObject(600), NumberObject(50)], b"l"), ([], b"S")]
additions += [([FloatObject(1.2)], b"w")]
stream.operations = additions + stream.operations
page[NameObject("/Contents")] = writer._add_object(stream)
with file.open("wb") as out:
writer.write(out)
tracked = {b"rg", b"RG", b"g", b"G", b"k", b"K", b"w", b"cm", b"m", b"l", b"re", b"S", b"f", b"Tm"}
def graphics(reader):
return [(tuple(operands), op) for operands, op in ContentStream(reader.pages[0].get_contents(), reader).operations if op in tracked]
before = PdfReader(file)
expected = graphics(before)
box = list(before.pages[0].mediabox)
report = apply_pdf_style(file, ExportOptions(font_mapping=mapping, legacy_gbk=True, print_theme="original"))
after = PdfReader(file)
assert report.modified and report.repaired_strings == 1
assert report.color_ops == 0
assert graphics(after) == expected
assert list(after.pages[0].mediabox) == box
assert "注意事项" in after.pages[0].extract_text()
def test_stroke_search_text_is_not_reported_as_visible_font_repair(tmp_path):
file=tmp_path/'stroke.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file))
font=writer.pages[0]['/Resources']['/Font']['/F1'].get_object()
font[NameObject('/BaseFont')]=NameObject('/fstroke0')
font[NameObject('/Widths')]=ArrayObject([NumberObject(600)]*256)
font[NameObject('/FirstChar')]=NumberObject(0)
with file.open('wb') as stream:writer.write(stream)
before=file.read_bytes()
with pytest.raises(ValueError,match='笔画'):
apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True))
assert file.read_bytes()==before
def test_used_form_stroke_font_cannot_bypass_repair_validation(tmp_path):
file=tmp_path/'form-stroke.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file));page=writer.pages[0]
font=page['/Resources']['/Font']['/F1'].get_object()
font[NameObject('/BaseFont')]=NameObject('/fstroke0')
font[NameObject('/Widths')]=ArrayObject([NumberObject(600)]*256)
font[NameObject('/FirstChar')]=NumberObject(0)
form=DecodedStreamObject();form.set_data(page.get_contents().get_data())
form.update({NameObject('/Type'):NameObject('/XObject'),NameObject('/Subtype'):NameObject('/Form'),NameObject('/BBox'):ArrayObject([NumberObject(0),NumberObject(0),NumberObject(640),NumberObject(220)]),NameObject('/Resources'):page['/Resources']})
page[NameObject('/Resources')]=DictionaryObject({NameObject('/XObject'):DictionaryObject({NameObject('/X1'):writer._add_object(form)})})
content=DecodedStreamObject();content.set_data(b'/X1 Do');page[NameObject('/Contents')]=writer._add_object(content)
with file.open('wb') as out:writer.write(out)
before=file.read_bytes()
with pytest.raises(ValueError,match='笔画'):
apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True))
assert file.read_bytes()==before
@pytest.mark.parametrize('family,advance',[
('Helvetica',31.892),('Courier-Bold',33.6),
])
def test_standard14_fonts_use_exact_afm_advance_without_guessing(family,advance):
from mentor_pdf_export.pdf_styles import _old_width
font=DictionaryObject({NameObject('/BaseFont'):NameObject('/'+family),NameObject('/Subtype'):NameObject('/Type1'),NameObject('/Encoding'):NameObject('/WinAnsiEncoding')})
assert _old_width(font,b'Wi12',14)==pytest.approx(advance)
def test_unknown_font_without_metrics_is_still_rejected():
from mentor_pdf_export.pdf_styles import _old_width
assert _old_width(DictionaryObject({NameObject('/BaseFont'):NameObject('/UnknownNoMetrics')}),b'Wi12',14) is None
def test_hidden_ascii_strokes_survive_mixed_chinese_repair_without_overlay(tmp_path):
file=tmp_path/'mixed.pdf';legacy_pdf(file,'注意事项')
writer=PdfWriter();writer.clone_document_from_reader(PdfReader(file));page=writer.pages[0]
font=DictionaryObject({NameObject('/Type'):NameObject('/Font'),NameObject('/Subtype'):NameObject('/TrueType'),NameObject('/BaseFont'):NameObject('/fstroke5'),NameObject('/Encoding'):NameObject('/WinAnsiEncoding'),NameObject('/FirstChar'):NumberObject(0),NameObject('/Widths'):ArrayObject([NumberObject(600)]*256)})
page['/Resources']['/Font'][NameObject('/F2')]=writer._add_object(font)
stream=ContentStream(page.get_contents(),writer)
stream.operations.extend([
([],b'BT'),([NameObject('/F1'),NumberObject(14)],b'Tf'),([ByteStringObject(b'POWER')],b'Tj'),([],b'ET'),
([],b'BT'),([NumberObject(3)],b'Tr'),([NameObject('/F2'),NumberObject(14)],b'Tf'),([ByteStringObject(b'POWER')],b'Tj'),([],b'ET'),([NumberObject(0)],b'Tr'),
])
stream.get_data();page[NameObject('/Contents')]=writer._add_object(stream)
with file.open('wb') as out:writer.write(out)
before=PdfReader(file);old=[(a,op) for a,op in ContentStream(before.pages[0].get_contents(),before).operations if op in (b'm',b'l',b're',b'RG',b'rg',b'Tr')]
report=apply_pdf_style(file,ExportOptions(font_mapping='arial',legacy_gbk=True,print_theme='reference'))
result=PdfReader(file)
assert '注意事项' in result.pages[0].extract_text()
assert report.font_strings==2 and report.preserved_ascii_stroke_strings==1
ops=ContentStream(result.pages[0].get_contents(),result).operations
assert old==[(a,op) for a,op in ops if op in (b'm',b'l',b're',b'RG',b'rg',b'Tr')]
assert any(op==b'Tj' and (a[0].original_bytes if hasattr(a[0],'original_bytes') else bytes(a[0]))==b'POWER' for a,op in ops)
+28
View File
@@ -31,3 +31,31 @@ def test_stroke_mode_uses_native_verified_attached_switch():
args=build_command(Path("engine.exe"),Path("a.prj"),Path("a.pdf"),ExportOptions(stroke_fonts=True))
assert "-uAll" in args
assert "-u" not in args and "-udx" not in args
def test_explicit_font_and_print_profile_modes():
options=ExportOptions(font_mapping="arial",print_theme="high_contrast")
assert options.font_mapping=="arial" and options.print_theme=="high_contrast"
def test_profile_modes_reject_unknown_names():
import pytest
with pytest.raises(ValueError,match="字体"):
ExportOptions(font_mapping="arail\nInjected value")
with pytest.raises(ValueError,match="配色"):
ExportOptions(print_theme="unknown")
def test_arial_profile_changes_only_copy_font_configuration(tmp_path):
ini=tmp_path/"dxpdf.ini";ini.write_text("FONT_CUSTOM_FONTS Courier-Bold\nFont_1 Courier-Bold\n")
write_profile(ini,ExportOptions(font_mapping="arial"))
lines=ini.read_text().splitlines()
assert "FONT_CUSTOM_FONTS Arial" in lines
assert "Font_1 Arial" in lines
def test_print_theme_controls_effective_background_mode():
args=build_command(Path("engine.exe"),Path("p.prj"),Path("p.pdf"),ExportOptions(color=2,print_theme="high_contrast"))
assert args[args.index("-c")+1]=="4"
args=build_command(Path("engine.exe"),Path("p.prj"),Path("p.pdf"),ExportOptions(print_theme="mono"))
assert args[args.index("-c")+1]=="3"
+68
View File
@@ -0,0 +1,68 @@
"""Regression: ordinary UI defaults must generate readable reference-style output."""
import os
import sys
import threading
import xml.etree.ElementTree as ET
from pathlib import Path
from pypdf import PdfReader
from pypdf.generic import ContentStream
from mentor_pdf_export.models import ExportOptions
from mentor_pdf_export.profiles import build_command
from mentor_pdf_export.pdf_styles import apply_pdf_style
from mentor_pdf_export.engine import run_engine
from mentor_pdf_export.ui import MainWindow
from test_pdf_styles import legacy_pdf
def test_font_repair_uses_native_mapped_text_not_dxd_stroke_fallback():
cmd=build_command(Path('sch2pdf.exe'),Path('demo.prj'),Path('demo.pdf'),ExportOptions(font_mapping='arial',legacy_gbk=True))
assert '-udx' not in cmd and '-uAll' not in cmd
def test_reference_palette_is_child_only_and_role_specific(tmp_path,monkeypatch):
from mentor_pdf_export.profiles import prepare_native_environment
monkeypatch.setenv('WDIR',r'D:\Mentor\standard')
monkeypatch.setenv('MENTOR_TEST_LICENSE','inherited')
before=dict(os.environ)
env=prepare_native_environment(tmp_path,ExportOptions(print_theme='reference'))
assert dict(os.environ)==before
cfg=Path(env['WDIR'].split(';')[0])
assert cfg.is_relative_to(tmp_path)
tree=ET.parse(cfg/'DxDesigner.xml')
def color(name):return tree.find(f"./DxDesigner/OBJECTS/object[@name='{name}']/key[@name='COLOR']").get('value')
assert color('NET')=='0xff0000'
assert color('PIN')=='0x008080'
assert color('LINE')=='0x0000ff'
assert color('BOX')=='0x800080'
assert color('CIRCLE')=='0x008000'
assert color('LABEL')=='0x008000'
assert color('ATTRIBUTE')=='0x388e8e' # Reference's inherited component values; pins remain #008080.
assert env['WDIR'].endswith(r';D:\Mentor\standard')
assert env['MENTOR_TEST_LICENSE']=='inherited'
assert prepare_native_environment(tmp_path,ExportOptions(print_theme='original')) is None
def test_engine_passes_environment_to_owned_child_only(tmp_path,monkeypatch):
monkeypatch.setenv('MENTOR_PDF_ENV_TEST','parent')
env=dict(os.environ);env['MENTOR_PDF_ENV_TEST']='child'
rc=run_engine([sys.executable,'-c',"import os;print(os.environ['MENTOR_PDF_ENV_TEST'])"],tmp_path,tmp_path/'logs',threading.Event(),10,env=env)
assert rc==0
assert (tmp_path/'logs/stdout.log').read_text().strip()=='child'
assert os.environ['MENTOR_PDF_ENV_TEST']=='parent'
def test_plain_ui_defaults_repair_chinese_without_recoloring_or_thickening(qtbot,tmp_path):
window=MainWindow();qtbot.addWidget(window)
opts=window.options()
assert opts.print_theme=='reference'
cmd=build_command(Path('sch2pdf.exe'),Path('工程.prj'),Path('工程.pdf'),opts)
assert '-udx' not in cmd
file=tmp_path/'native.pdf';legacy_pdf(file,'注意事项 音频 Ω μ ± ×')
before=PdfReader(file);ops=ContentStream(before.pages[0].get_contents(),before).operations
geometry=[(a,b) for a,b in ops if b in (b'm',b'l',b're',b'w',b'rg',b'RG')]
report=apply_pdf_style(file,opts)
reader=PdfReader(file);text=reader.pages[0].extract_text()
assert '注意事项' in text and '音频' in text
assert all(s in text for s in ('Ω','μ','±','×'))
assert report.repaired_strings==1 and report.fallback_strings==1
assert geometry==[(a,b) for a,b in ContentStream(reader.pages[0].get_contents(),reader).operations if b in (b'm',b'l',b're',b'w',b'rg',b'RG')]
+124
View File
@@ -0,0 +1,124 @@
from pathlib import Path
import struct
import tomllib
from PySide6.QtCore import QSize
from PySide6.QtGui import QIcon
ROOT = Path(__file__).parents[1]
def test_official_version_and_user_facing_title(qtbot):
from mentor_pdf_export import __version__
from mentor_pdf_export.ui import MainWindow
assert __version__ == "1.0.0"
assert tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))["project"]["version"] == __version__
window = MainWindow()
qtbot.addWidget(window)
assert window.windowTitle() == "Mentor PDF 批量导出 · v1.0.0"
assert not window.windowIcon().isNull()
def test_icon_contains_all_shell_and_taskbar_sizes(qapp):
from mentor_pdf_export.branding import icon_path, application_icon
data = icon_path().read_bytes()
reserved, kind, count = struct.unpack_from("<HHH", data)
assert (reserved, kind) == (0, 1)
sizes = set()
for index in range(count):
width, height, _, _, _, bits, length, offset = struct.unpack_from("<BBBBHHII", data, 6 + 16 * index)
assert bits == 32 and width == height
assert offset + length <= len(data)
assert data[offset:offset + 8] == b"\x89PNG\r\n\x1a\n"
sizes.add(width or 256)
assert sizes == {16, 24, 32, 48, 64, 128, 256}
icon = application_icon()
assert not icon.isNull()
for size in sizes:
assert not icon.pixmap(QSize(size, size)).isNull()
def test_application_metadata_and_global_icon(qapp):
from mentor_pdf_export.branding import configure_application, APP_ID
configure_application(qapp)
assert qapp.applicationVersion() == "1.0.0"
assert qapp.applicationDisplayName() == "Mentor PDF 批量导出"
assert qapp.applicationName() == "MentorPDFExporter"
assert not qapp.windowIcon().isNull()
assert APP_ID == "simgreek.MentorPDFExporter"
def test_windows_app_id_is_explicit_and_stable(monkeypatch):
from mentor_pdf_export import branding
calls = []
class Function:
def __call__(self, app_id):
calls.append(app_id)
return 0
class Shell:
SetCurrentProcessExplicitAppUserModelID = Function()
monkeypatch.setattr(branding.sys, "platform", "win32")
monkeypatch.setattr(branding, "_shell32", lambda: Shell())
assert branding.set_windows_app_id()
assert calls == [branding.APP_ID]
def test_app_id_skips_non_windows(monkeypatch):
from mentor_pdf_export import branding
monkeypatch.setattr(branding.sys, "platform", "linux")
monkeypatch.setattr(branding, "_shell32", lambda: (_ for _ in ()).throw(AssertionError("Windows API called")))
assert not branding.set_windows_app_id()
def test_pyinstaller_includes_application_icon_and_windows_metadata():
spec = (ROOT / "packaging/MentorPDFExporter.spec").read_text(encoding="utf8")
assert "mentor_pdf_export/assets" in spec
assert "icon=" in spec and "version=version_info" in spec
config = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))
assert "assets/*.ico" in config["tool"]["setuptools"]["package-data"]["mentor_pdf_export"]
def test_cli_uses_release_wording(capsys):
import pytest
from mentor_pdf_export.cli import main
with pytest.raises(SystemExit) as exit_info:
main(["--help"])
assert exit_info.value.code == 0
output = capsys.readouterr().out
assert "批量导出工具" in output and "测试工具" not in output
def test_windows_app_id_failure_is_nonfatal(monkeypatch):
from mentor_pdf_export import branding
class Function:
def __call__(self, app_id):
return -1
class Shell:
SetCurrentProcessExplicitAppUserModelID = Function()
monkeypatch.setattr(branding.sys, "platform", "win32")
monkeypatch.setattr(branding, "_shell32", lambda: Shell())
assert not branding.set_windows_app_id()
def test_ui_smoke_fails_when_application_icon_is_missing(qapp, tmp_path, monkeypatch):
import json
from mentor_pdf_export import branding, ui
from mentor_pdf_export.cli import main
monkeypatch.setattr(branding, "application_icon", lambda: QIcon())
monkeypatch.setattr(ui, "application_icon", lambda: QIcon())
report = tmp_path / "smoke.json"
rc = main(["--ui-smoke", str(tmp_path / "ui.png"), "--report", str(report)])
data = json.loads(report.read_text(encoding="utf8"))
assert data["screenshot_saved"] and not data["application_icon"] and not data["window_icon"]
assert rc != 0
def test_windows_ui_smoke_requires_taskbar_identity(qapp, tmp_path, monkeypatch):
import sys
import pytest
from mentor_pdf_export import branding
from mentor_pdf_export.cli import main
if sys.platform != "win32":
pytest.skip("Windows taskbar identity")
monkeypatch.setattr(branding, "set_windows_app_id", lambda: False)
assert main(["--ui-smoke", str(tmp_path / "ui.png")]) != 0
+111
View File
@@ -0,0 +1,111 @@
from pathlib import Path
import importlib.util
import pytest
ROOT = Path(__file__).parents[1]
def release_module():
spec = importlib.util.spec_from_file_location("build_release", ROOT / "packaging/build_release.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def skeleton(tmp_path):
(tmp_path / "MentorPDFExporter.exe").write_bytes(b"stub")
assets = tmp_path / "_internal/mentor_pdf_export/assets"
assets.mkdir(parents=True)
(assets / "app.ico").write_bytes(b"icon")
return tmp_path
def test_release_version_matches_official_metadata():
assert release_module().project_version() == "1.0.0"
requirements = (ROOT / "packaging/requirements-release.txt").read_text(encoding="utf8")
assert "cryptography==45.0.7" in requirements and "cffi==2.1.1" in requirements
@pytest.mark.parametrize("name", ["private.prj", "library.lmc", "output.pdf", "Arial.ttf", "SimSun.ttc", "font.otf", "sch2pdf.exe"])
def test_release_rejects_engineering_data_fonts_and_mentor(tmp_path, name):
bundle = skeleton(tmp_path)
(bundle / name).write_bytes(b"private")
with pytest.raises(ValueError):
release_module().validate_bundle(bundle)
def test_release_requires_packaged_window_icon(tmp_path):
bundle = skeleton(tmp_path)
(bundle / "_internal/mentor_pdf_export/assets/app.ico").unlink()
with pytest.raises(ValueError, match="icon"):
release_module().validate_bundle(bundle)
def test_release_allows_runtime_library_archive(tmp_path):
bundle = skeleton(tmp_path)
(bundle / "_internal/base_library.zip").write_bytes(b"runtime")
release_module().validate_bundle(bundle)
@pytest.mark.parametrize("relative", ["license.lic", "license.dat", "database/icdb.dat", "runs/report.json", ".git/config", "_internal/runs/report.json", "_internal/private.dat", "unexpected.txt"])
def test_release_rejects_private_license_database_logs_and_git(tmp_path, relative):
bundle = skeleton(tmp_path)
private = bundle / relative
private.parent.mkdir(parents=True, exist_ok=True)
private.write_bytes(b"private")
with pytest.raises(ValueError):
release_module().validate_bundle(bundle)
def test_release_runtime_must_match_build_allowlist(tmp_path):
bundle = skeleton(tmp_path)
module = release_module()
allowed = {p.relative_to(bundle).as_posix(): module.sha256(p) for p in bundle.rglob("*") if p.is_file()}
(bundle / "_internal/unknown.dll").write_bytes(b"not collected by PyInstaller")
with pytest.raises(ValueError):
module.validate_bundle(bundle, runtime_files=allowed)
def make_archive(path, bundle, *, omit=None, extra=None, duplicate=None, changed=None):
import zipfile
with zipfile.ZipFile(path, "w") as archive:
for file in bundle.rglob("*"):
if not file.is_file() or file.name == omit:
continue
name = bundle.name + "/" + file.relative_to(bundle).as_posix()
archive.writestr(name, b"tampered" if file.name == changed else file.read_bytes())
if file.name == duplicate:
archive.writestr(name, file.read_bytes())
if extra:
archive.writestr(extra, b"private")
def test_archive_matches_complete_verified_directory(tmp_path):
bundle = tmp_path / "release"
bundle.mkdir()
skeleton(bundle)
archive = tmp_path / "release.zip"
make_archive(archive, bundle)
release_module().validate_archive(archive, bundle)
@pytest.mark.parametrize("case", ["missing", "extra", "duplicate", "traversal", "modified"])
def test_archive_rejects_incomplete_extra_duplicate_unsafe_or_changed_members(tmp_path, case):
import warnings
bundle = tmp_path / "release"
bundle.mkdir()
skeleton(bundle)
archive = tmp_path / "release.zip"
options = {
"missing": {"omit": "app.ico"},
"extra": {"extra": "release/license.lic"},
"duplicate": {"duplicate": "MentorPDFExporter.exe"},
"traversal": {"extra": "release/../private.txt"},
"modified": {"changed": "app.ico"},
}[case]
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
make_archive(archive, bundle, **options)
with pytest.raises(ValueError):
release_module().validate_archive(archive, bundle)
+37
View File
@@ -0,0 +1,37 @@
from pathlib import Path
import importlib.util
import pytest
ROOT = Path(__file__).parents[1]
def publisher():
spec = importlib.util.spec_from_file_location("publish_release", ROOT / "packaging/publish_release.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize("value", ["../other", "org/name", "org?token=x", "", "name with spaces"])
def test_repository_names_cannot_change_request_paths(value):
with pytest.raises(ValueError):
publisher().validate_name(value)
def test_expected_organization_name_is_valid():
assert publisher().validate_name("simgreek") == "simgreek"
def test_attachment_uses_gitea_multipart_field(tmp_path):
file = tmp_path / "release.zip"
file.write_bytes(b"ZIP-CONTENT")
body, content_type = publisher().multipart_attachment(file, "safe-boundary")
assert 'boundary=safe-boundary' in content_type
assert b'name="attachment"; filename="release.zip"' in body
assert b"ZIP-CONTENT" in body and body.endswith(b"--safe-boundary--\r\n")
def test_server_redirect_never_forwards_credentials():
handler = publisher().NoRedirect()
assert handler.redirect_request(None, None, 302, "redirect", {}, "https://other-host.invalid") is None
+61
View File
@@ -0,0 +1,61 @@
from mentor_pdf_export.source_policy import classify_source_changes
import pytest
@pytest.mark.parametrize('kind, name', [
('modified','database/icdb.dat'),
('modified','database/cdbsvr/events/events.dat'),
('added','database/cdbsvr/events/events.idx'),
('removed','database/cdbsvr/events/events.idx'),
('modified','database/cdbsvr/sAddress.adr'),
('added','database/cdbsvr/sAddress.adr'),
('removed','database/cdbsvr/sAddress.adr'),
('added','database/cdbsvr/log/new/run.txt'),
('removed','database/cdbsvr/log/old/run.txt'),
('added','database/cdbsvr/dbcheck/new/check.txt'),
('added','database/cdbsvr/dbupgrade/new/upgrade.txt'),
('added','database/cdbsvr/plog/run.txt'),
('added','database/cdbback/native.zip'),
])
def test_observed_native_updates_are_nonblocking_but_recorded(kind, name):
from mentor_pdf_export.source_policy import classify_source_changes
changes={'modified':[], 'added':[], 'removed':[]}; changes[kind]=[name]
accepted, blocked=classify_source_changes(changes,'database')
assert accepted==changes and not any(blocked.values())
accepted, blocked=classify_source_changes(changes,'database',strict=True)
assert not any(accepted.values()) and blocked==changes
@pytest.mark.parametrize('kind, name', [
('modified','board.prj'), ('modified','dxpdf.ini'),
('modified','colors.def'), ('modified','sheet.sch'),
('added','database/icdb.dat'), ('removed','database/icdb.dat'),
('modified','database/cdbback/old.zip'), ('removed','database/cdbback/old.zip'),
('modified','database/cdbsvr/design.dat'),
('modified','other/database/icdb.dat'),
('modified','database/../board.prj'),
('modified','database/cdbsvr/log/../design.dat'),
])
def test_unknown_design_and_deleted_database_changes_remain_blocking(kind, name):
from mentor_pdf_export.source_policy import classify_source_changes
changes={'modified':[], 'added':[], 'removed':[]}; changes[kind]=[name]
accepted, blocked=classify_source_changes(changes,'database')
assert not any(accepted.values()) and blocked==changes
def test_uses_declared_database_directory_and_windows_case_insensitivity():
from mentor_pdf_export.source_policy import classify_source_changes
changes={'modified':['DATA/ICDB.DAT','database/icdb.dat'],'added':[],'removed':[]}
accepted, blocked=classify_source_changes(changes,'data')
assert accepted['modified']==['DATA/ICDB.DAT']
assert blocked['modified']==['database/icdb.dat']
@pytest.mark.parametrize('kind',['added','modified','removed'])
def test_native_backup_coordination_record_is_warning_not_design_edit(kind):
changes={k:[] for k in ('added','modified','removed')}
changes[kind]=['database/cdbsvr/backup.lck','database/cdbsvr/unknown.lck','other/cdbsvr/backup.lck']
accepted,blocked=classify_source_changes(changes,'database')
assert accepted[kind]==['database/cdbsvr/backup.lck']
assert blocked[kind]==['database/cdbsvr/unknown.lck','other/cdbsvr/backup.lck']
accepted,blocked=classify_source_changes(changes,'database',strict=True)
assert not accepted[kind] and blocked[kind]==changes[kind]
+445 -4
View File
@@ -1,20 +1,24 @@
import threading
from pathlib import Path
import pytest
from pypdf import PdfWriter
from PySide6.QtCore import Qt
from PySide6.QtGui import QPalette
from PySide6.QtWidgets import QFileDialog, QLabel
from mentor_pdf_export.ui import MainWindow
from mentor_pdf_export.exporter import Exporter
from mentor_pdf_export.models import ExportResult
def runner(args, cwd, log_dir, cancel, timeout, on_event=None):
def runner(args, cwd, log_dir, cancel, timeout, on_event=None, *, env=None):
writer = PdfWriter(); writer.add_blank_page(width=500,height=400)
with Path(args[args.index("-a")+1]).open("wb") as f:
writer.write(f)
return 0
def make_window(qtbot, tmp_path, factory=None):
window = MainWindow(root=str(tmp_path), output=str(tmp_path / "pdfs"), runs_root=tmp_path.parent / (tmp_path.name + "-runs"), exporter_factory=factory)
def make_window(qtbot, tmp_path, factory=None, library=None):
window = MainWindow(root=str(tmp_path), output=str(tmp_path / "pdfs"), runs_root=tmp_path.parent / (tmp_path.name + "-runs"), exporter_factory=factory, library=library, font_mapping="preserve", print_theme="original", legacy_gbk=False)
qtbot.addWidget(window); window.show()
return window
@@ -47,6 +51,9 @@ def test_export_worker_result_and_buttons(qtbot, project_factory, tmp_path):
assert window.busy
assert not window.start_button.isEnabled()
assert not window.options_group.isEnabled()
assert not window.font_mapping_combo.isEnabled()
assert not window.print_theme_combo.isEnabled()
assert not window.legacy_gbk_check.isEnabled()
qtbot.waitUntil(lambda: not window.busy,timeout=10000)
assert window.table.item(0,3).text()=="成功"
assert window.start_button.isEnabled()
@@ -58,7 +65,7 @@ def test_export_worker_result_and_buttons(qtbot, project_factory, tmp_path):
def test_cancel_signal_is_requested(qtbot, project_factory, tmp_path):
project_factory()
started=threading.Event()
def waiting(args,cwd,log_dir,cancel,timeout,on_event=None):
def waiting(args,cwd,log_dir,cancel,timeout,on_event=None, *, env=None):
started.set()
assert cancel.wait(5)
raise InterruptedError("任务已停止")
@@ -101,3 +108,437 @@ def test_ui_preflights_all_source_paths_before_queue(qtbot,project_factory,tmp_p
qtbot.waitUntil(lambda:not window.busy,timeout=10000)
assert not unexpectedly_started
assert window.worker is None
def test_direct_mode_has_no_library_replacement_controls(qtbot,tmp_path):
window=make_window(qtbot,tmp_path)
assert not hasattr(window,'library_edit')
assert not hasattr(window,'library_toggle')
assert '原工程' in window.root_edit.toolTip()
assert window.options().library_override==''
def test_constructor_rejects_library_replacement_in_direct_mode(qtbot,tmp_path):
with pytest.raises(ValueError,match='依赖库'):
MainWindow(root=tmp_path,library=tmp_path/'matching.lmc')
def test_library_information_is_read_only(qtbot,tmp_path):
window=make_window(qtbot,tmp_path)
assert not hasattr(window, 'library_help')
assert '不替换库' in window.root_edit.toolTip()
assert not any('依赖库' in label.text() for label in window.findChildren(QLabel) if label.isVisible())
assert not hasattr(window,'choose_library')
def test_profile_defaults_preserve_existing_export_modes(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert window.font_mapping_combo.currentData() == "preserve"
assert window.print_theme_combo.currentData() == "original"
options = window.options()
assert options.font_mapping == "preserve"
assert options.print_theme == "original"
assert options.color == 4
assert [window.color_combo.itemData(i) for i in range(window.color_combo.count())] == [4, 3, 1, 2]
assert not hasattr(window, "profile_warning_label")
@pytest.mark.parametrize("label, mapping", [
("原映射", "preserve"),
("Arial+中文回退(推荐)", "arial"),
("宋体(中文对照)", "simsun"),
("微软雅黑(中文对照)", "msyh"),
])
def test_font_mapping_flows_to_options(qtbot, tmp_path, label, mapping):
window = make_window(qtbot, tmp_path)
index = window.font_mapping_combo.findText(label)
assert index >= 0
window.font_mapping_combo.setCurrentIndex(index)
assert window.options().font_mapping == mapping
@pytest.mark.parametrize("theme", ["original", "high_contrast", "mono"])
def test_print_theme_enforces_color_and_restores_original_choice(qtbot, tmp_path, theme):
window = make_window(qtbot, tmp_path)
index = window.print_theme_combo.findData(theme)
assert index >= 0
window.print_theme_combo.setCurrentIndex(index)
for color_index, existing_color in enumerate([4, 3, 1, 2]):
window.color_combo.setCurrentIndex(color_index)
options = window.options()
assert options.print_theme == theme
expected_color = {"high_contrast": 4, "mono": 3}.get(theme, existing_color)
assert options.color == expected_color
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("original"))
assert window.options().color == 2
def test_profile_tooltips_explain_processing_and_sample_limits(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert window.print_theme_combo.findText("白底高对比(可选)") >= 0
for mapping in ("arial", "simsun", "msyh"):
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
assert not hasattr(window, "profile_warning_label")
explanation = window.font_mapping_combo.toolTip()
assert "发布前" in explanation and "文字编码" in explanation
assert "样本" in explanation and "其他工程" in explanation
for detail in ("矢量", "坐标", "书签", "注释", "不添加白色遮罩", "不栅格化"):
assert detail in explanation
assert "未验证" not in explanation and "未生效" not in explanation
assert "不保证修复中文" not in explanation
if mapping == "arial":
assert "Arial" in explanation and "宋体" in explanation and "17" in explanation
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("preserve"))
assert not hasattr(window, "profile_warning_label")
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("high_contrast"))
assert not hasattr(window, "profile_warning_label")
assert "深色前景" in window.font_mapping_combo.toolTip()
assert "浅色填充" in window.font_mapping_combo.toolTip()
assert "0.35pt" in window.font_mapping_combo.toolTip()
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("mono"))
assert not hasattr(window, "profile_warning_label")
assert "黑白" in window.font_mapping_combo.toolTip()
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("original"))
assert not hasattr(window, "profile_warning_label")
@pytest.mark.parametrize("kind", ["scan", "batch"])
def test_new_controls_lock_and_restore_with_busy_state(qtbot, tmp_path, kind):
window = make_window(qtbot, tmp_path)
controls = (
window.root_edit, window.engine_edit,
window.font_mapping_combo, window.print_theme_combo, window.legacy_gbk_check,
)
window._set_busy(True, kind)
assert all(not control.isEnabled() for control in controls)
assert window.stop_button.isEnabled() == (kind == "batch")
window._set_busy(False, kind)
assert all(control.isEnabled() for control in controls)
def test_blue_gray_palette_has_blue_primary_and_white_cards(qtbot, project_factory, tmp_path):
project_factory()
window = make_window(qtbot, tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 1 and not window.busy, timeout=10000)
qtbot.wait(20)
assert window.start_button.palette().color(QPalette.Button).name() == "#2563eb"
assert window.palette().color(QPalette.Window).name() == "#f1f5f9"
assert window.paths_group.palette().color(QPalette.Window).name() == "#ffffff"
@pytest.mark.parametrize("status, color", [
("success", "#16a34a"), ("skipped", "#d97706"),
("uncertain", "#d97706"), ("failed", "#dc2626"),
("timeout", "#dc2626"),
])
def test_result_status_keeps_semantic_colors(qtbot, project_factory, tmp_path, status, color):
project_factory()
window = make_window(qtbot, tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 1 and not window.busy, timeout=10000)
window._item_result(0, ExportResult(project="board", status=status, message="对照结果"))
assert window.table.item(0, 3).foreground().color().name() == color
def test_selection_and_advanced_controls_do_not_reset_scroll(qtbot, project_factory, tmp_path):
for number in range(45):
project_factory(f"board-{number:02d}")
window = make_window(qtbot, tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 45 and not window.busy, timeout=10000)
scrollbar = window.table.verticalScrollBar()
qtbot.waitUntil(lambda: scrollbar.maximum() > 0)
scrollbar.setValue(scrollbar.maximum() // 2)
position = scrollbar.value()
item = window.table.item(25, 0)
item.setCheckState(Qt.Unchecked)
qtbot.mouseClick(window.select_all_button, Qt.LeftButton)
assert scrollbar.value() == position
assert window.table.item(25, 0) is item
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
qtbot.wait(20)
assert scrollbar.value() == position
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
qtbot.wait(20)
assert scrollbar.value() == position
assert window.selected_count() == 45
@pytest.mark.parametrize("theme", ["original", "high_contrast", "mono"])
def test_expanded_advanced_settings_leave_queue_rows_visible(qtbot, project_factory, tmp_path, theme):
for number in range(6):
project_factory(f"board-{number}")
window = make_window(qtbot, tmp_path)
qtbot.mouseClick(window.advanced_button, Qt.LeftButton)
assert window.advanced_panel.isVisible()
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 6 and not window.busy, timeout=10000)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData("arial"))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(theme))
qtbot.wait(50)
assert window.table.viewport().visibleRegion().boundingRect().height() >= 2 * window.table.rowHeight(0)
@pytest.mark.parametrize("theme", ["original", "high_contrast", "mono"])
def test_color_selector_only_enabled_for_original_and_restores_after_busy(qtbot, tmp_path, theme):
window = make_window(qtbot, tmp_path)
window.color_combo.setCurrentIndex(window.color_combo.findData(2))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(theme))
assert window.color_combo.isEnabled() == (theme == "original")
assert window.color_combo.currentData() == 2
for kind in ("scan", "batch"):
window._set_busy(True, kind)
assert not window.color_combo.isEnabled()
window._set_busy(False, kind)
assert window.color_combo.isEnabled() == (theme == "original")
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData("original"))
assert window.color_combo.isEnabled()
assert window.options().color == 2
@pytest.mark.parametrize("mapping, theme", [
("arial", "high_contrast"), ("simsun", "mono"),
("msyh", "original"), ("preserve", "original"),
])
def test_constructor_accepts_explicit_profile_defaults(qtbot, tmp_path, mapping, theme):
window = MainWindow(root=tmp_path, output=tmp_path / "pdfs", font_mapping=mapping, print_theme=theme)
qtbot.addWidget(window)
window.show()
assert window.font_mapping_combo.currentData() == mapping
assert window.print_theme_combo.currentData() == theme
options = window.options()
assert options.font_mapping == mapping
assert options.print_theme == theme
assert options.color == (3 if theme == "mono" else 4)
assert window.color_combo.isEnabled() == (theme == "original")
assert not hasattr(window, "profile_warning_label")
@pytest.mark.parametrize("defaults, message", [
({"font_mapping": "arail"}, "字体"),
({"print_theme": "unknown"}, "配色"),
])
def test_constructor_rejects_unknown_profile_defaults(qtbot, defaults, message):
with pytest.raises(ValueError, match=message):
MainWindow(**defaults)
@pytest.mark.parametrize("mapping, theme", [
("arial", "original"), ("preserve", "high_contrast"), ("msyh", "mono"),
])
def test_profile_tooltips_expose_limited_compatibility_scope(qtbot, tmp_path, mapping, theme):
window = make_window(qtbot, tmp_path)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(theme))
assert not hasattr(window, "profile_warning_label")
assert "兼容范围有限" in window.font_mapping_combo.toolTip()
assert "其他工程" in window.font_mapping_combo.toolTip()
explanation = window.font_mapping_combo.toolTip()
assert "不代表所有 PDF" in explanation
assert "字体" in explanation and "文字结构" in explanation
assert "样张" in explanation
assert "未验证" not in explanation and "未生效" not in explanation
def test_legacy_gbk_is_explicit_and_respects_disabled_override(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert window.legacy_gbk_check.text() == "CP936 / GBK 修复"
assert not window.legacy_gbk_check.isChecked()
assert window.options().legacy_gbk is False
explanation = window.legacy_gbk_check.toolTip()
assert "WinAnsi" in explanation and "±" in explanation and "×" in explanation
assert "不适用于" in explanation
assert "已确认" in explanation
assert "Arial" in explanation and "不等于编码修复" in explanation
@pytest.mark.parametrize("mapping", ["arial", "simsun", "msyh"])
def test_font_mapping_alone_does_not_enable_encoding_repair(qtbot, tmp_path, mapping):
window = make_window(qtbot, tmp_path)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
assert window.options().font_mapping == mapping
assert window.options().legacy_gbk is False
assert not window.legacy_gbk_check.isChecked()
assert "不自动修复编码" in window.font_mapping_combo.toolTip()
@pytest.mark.parametrize("mapping", ["arial", "simsun", "msyh"])
def test_explicit_legacy_gbk_flows_to_options(qtbot, tmp_path, mapping):
window = make_window(qtbot, tmp_path)
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
# Matches the CLI follow-up: explicitly opt in after constructing the window.
window.legacy_gbk_check.setChecked(True)
assert window.options().legacy_gbk is True
assert window.options().font_mapping == mapping
assert "CP936 / GBK" in window.font_mapping_combo.toolTip()
assert "修复" in window.font_mapping_combo.toolTip()
window.legacy_gbk_check.setChecked(False)
assert window.options().legacy_gbk is False
assert "不自动修复编码" in window.font_mapping_combo.toolTip()
def test_legacy_gbk_rejects_preserve_without_silently_changing_font(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
window.legacy_gbk_check.setChecked(True)
assert window.font_mapping_combo.currentData() == "preserve"
with pytest.raises(ValueError) as error:
window.options()
message = str(error.value)
for choice in ("Arial", "SimSun", "YaHei"):
assert choice in message
assert "选择" in message
window.legacy_gbk_check.setChecked(False)
assert window.options().legacy_gbk is False
def test_recommended_constructor_profiles_respect_disabled_legacy_gbk_override(qtbot, tmp_path):
window = MainWindow(root=tmp_path, font_mapping="arial", print_theme="high_contrast", legacy_gbk=False)
qtbot.addWidget(window)
window.show()
assert not window.legacy_gbk_check.isChecked()
assert window.options().legacy_gbk is False
assert window.options().color == 4
assert "不自动修复编码" in window.font_mapping_combo.toolTip()
def test_reference_palette_is_recommended_and_font_repair_is_independent(qtbot, tmp_path):
window = MainWindow(root=tmp_path);qtbot.addWidget(window);window.show()
assert window.print_theme_combo.currentText() == "工程参考配色(推荐)"
explanation = window.print_theme_combo.toolTip()
for detail in ("红色", "青绿色", "原生线宽", "界面", "字体", "子进程"):
assert detail in explanation
window.legacy_gbk_check.setChecked(False)
assert window.options().print_theme == "reference"
assert window.options().color == 4
assert not window.options().legacy_gbk
assert "子进程" in window.font_mapping_combo.toolTip()
def test_direct_mode_discloses_native_database_write_risk(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert not hasattr(window, "source_warning_label")
text = window.strict_source_check.toolTip()
for detail in ("原生引擎", "数据库", "待核验", "不发布"):
assert detail in text
def test_heading_has_no_engine_status_badge(qtbot, tmp_path):
window = make_window(qtbot, tmp_path)
assert not hasattr(window, "environment_label")
assert not window.findChildren(QLabel, "badge")
assert not any("已找到 Mentor" in label.text() for label in window.findChildren(QLabel))
@pytest.mark.parametrize("kind", ["scan", "batch"])
def test_busy_queue_can_scroll_but_cannot_change_selection(qtbot, project_factory, tmp_path, kind):
for number in range(45):
project_factory(f"queue-{number:02d}")
window = make_window(qtbot, tmp_path)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 45 and not window.busy, timeout=10000)
scrollbar = window.table.verticalScrollBar()
qtbot.waitUntil(lambda: scrollbar.maximum() > 0)
before = [window.table.item(row, 0).checkState() for row in range(45)]
window._set_busy(True, kind)
try:
assert window.table.isEnabled()
assert scrollbar.isEnabled()
assert not window.select_all_button.isEnabled()
assert not window.clear_button.isEnabled()
assert not window.select_failed_button.isEnabled()
assert all(not (window.table.item(row, 0).flags() & Qt.ItemIsUserCheckable) for row in range(45))
scrollbar.setFocus()
qtbot.keyClick(scrollbar, Qt.Key_End)
assert scrollbar.value() == scrollbar.maximum()
qtbot.keyClick(scrollbar, Qt.Key_Home)
assert scrollbar.value() == scrollbar.minimum()
window.table.setCurrentCell(0, 0)
rect = window.table.visualItemRect(window.table.item(0, 0))
qtbot.mouseClick(window.table.viewport(), Qt.LeftButton, pos=rect.center())
qtbot.keyClick(window.table, Qt.Key_Space)
assert [window.table.item(row, 0).checkState() for row in range(45)] == before
finally:
window._set_busy(False, kind)
assert all(window.table.item(row, 0).flags() & Qt.ItemIsUserCheckable for row in range(45))
window.table.setCurrentCell(0, 0)
qtbot.keyClick(window.table, Qt.Key_Space)
assert window.table.item(0, 0).checkState() == Qt.Unchecked
def test_running_worker_keeps_queue_browsable_and_shows_direct_mode(qtbot, project_factory, tmp_path):
for number in range(30):
project_factory(f"active-{number:02d}")
started = threading.Event()
def waiting(args, cwd, log_dir, cancel, timeout, on_event=None, *, env=None):
started.set()
if cancel.wait(30):
raise InterruptedError("任务已停止")
raise TimeoutError("test worker did not receive stop")
window = make_window(qtbot, tmp_path, lambda engine, runs: Exporter(engine, runs, runner=waiting))
engine = tmp_path / "sch2pdf.exe"
engine.write_bytes(b"fake")
window.engine_edit.setText(str(engine))
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 30 and not window.busy, timeout=10000)
window.start_export()
try:
qtbot.waitUntil(started.is_set, timeout=10000)
assert window.busy and window.table.isEnabled()
scrollbar = window.table.verticalScrollBar()
scrollbar.setFocus()
qtbot.keyClick(scrollbar, Qt.Key_End)
assert scrollbar.maximum() > 0 and scrollbar.value() == scrollbar.maximum()
assert "直接" in window.status_label.text()
assert "副本" not in window.status_label.text()
assert "副本" not in window.table.item(0, 4).text()
assert "副本" not in window.log.placeholderText()
finally:
window.stop_export()
qtbot.waitUntil(lambda: not window.busy, timeout=10000)
assert window.table.item(0, 0).flags() & Qt.ItemIsUserCheckable
def test_native_update_warning_is_success_not_uncertain_in_ui(qtbot,project_factory,tmp_path):
project_factory();window=make_window(qtbot,tmp_path);window.scan_projects()
qtbot.waitUntil(lambda:window.table.rowCount()==1 and not window.busy,timeout=10000)
result=ExportResult(project='board',status='success',message='PDF valid; native database updated, not read-only',pages=1,warnings=('native update',))
window._item_result(0,result)
assert window.table.item(0,3).text()=='成功(有提示)'
assert window.table.columnWidth(3) >= 110
assert window.table.item(0,3).foreground().color().name()=='#d97706'
assert '1 页' in window.table.item(0,4).text()
assert 'native database' in window.table.item(0,4).toolTip()
def test_strict_source_check_is_optional_and_locks_during_export(qtbot,tmp_path):
window=make_window(qtbot,tmp_path)
assert not window.strict_source_check.isChecked() and not window.options().strict_source
assert '不阻止' in window.strict_source_check.toolTip()
window.strict_source_check.setChecked(True)
assert window.options().strict_source and '严格' in window.strict_source_check.toolTip()
window._set_busy(True)
assert not window.strict_source_check.isEnabled()
window._set_busy(False)
assert window.strict_source_check.isEnabled()
def test_batch_native_update_warnings_publish_and_count_as_success(qtbot,project_factory,tmp_path):
project_factory('one');project_factory('two')
def updating(args,cwd,logs,cancel,timeout,on_event=None, *, env=None):
rc=runner(args,cwd,logs,cancel,timeout,on_event)
(Path(cwd)/'database/icdb.dat').write_bytes(b'native update')
return rc
window=make_window(qtbot,tmp_path,lambda engine,runs:Exporter(engine,runs,runner=updating))
engine=tmp_path/'sch2pdf.exe';engine.write_bytes(b'fake');window.engine_edit.setText(str(engine))
window.scan_projects();qtbot.waitUntil(lambda:window.table.rowCount()==2 and not window.busy,timeout=10000)
window.start_export();qtbot.waitUntil(lambda:not window.busy,timeout=10000)
assert [window.table.item(row,3).text() for row in range(2)]==['成功(有提示)']*2
assert '成功 2' in window.status_label.text() and '有提示 2' in window.status_label.text()
assert all(Path(r.output).is_file() and r.warnings for r in window.worker.results)
+239
View File
@@ -0,0 +1,239 @@
from pathlib import Path
import pytest
from PySide6.QtCore import QPoint, Qt
from PySide6.QtWidgets import QLabel, QPushButton
from pypdf import PdfWriter
from mentor_pdf_export.exporter import Exporter
from mentor_pdf_export.models import ExportResult
from mentor_pdf_export.ui import MainWindow
@pytest.fixture
def compact_window(qtbot, tmp_path):
window = MainWindow(
root=tmp_path, output=tmp_path / "pdfs",
runs_root=tmp_path.parent / (tmp_path.name + "-runs"),
)
qtbot.addWidget(window)
window.show()
qtbot.waitUntil(lambda: window.isVisible())
return window
def visible_labels(window):
return [label.text() for label in window.findChildren(QLabel) if label.isVisible()]
@pytest.mark.parametrize("mapping,theme,strict", [
("arial", "reference", False), ("simsun", "high_contrast", True),
("preserve", "original", False), ("msyh", "mono", True),
])
def test_no_explanatory_paragraphs_in_any_profile(compact_window, mapping, theme, strict):
window = compact_window
window.font_mapping_combo.setCurrentIndex(window.font_mapping_combo.findData(mapping))
window.print_theme_combo.setCurrentIndex(window.print_theme_combo.findData(theme))
window.strict_source_check.setChecked(strict)
forbidden = (
"直接导出原工程", "依赖库", "默认工程参考配色", "发布前", "兼容范围",
"源文件变化", "原生引擎可能", "有效许可证", "不创建副本", "样本",
)
labels = visible_labels(window)
assert not [text for text in labels if any(phrase in text for phrase in forbidden)]
assert all(not label.wordWrap() for label in window.findChildren(QLabel) if label.isVisible())
assert not any("引擎" in text for text in labels if "导出引擎" != text)
def test_default_geometry_prioritizes_queue_and_compact_log(compact_window, qtbot):
window = compact_window
window.resize(1200, 820)
qtbot.wait(30)
assert window.table.height() >= 330
assert 60 <= window.log.height() <= 100
assert window.table.height() >= 3 * window.log.height()
assert window.table.visibleRegion().boundingRect().height() == window.table.height()
assert window.font_mapping_combo.currentData() == "arial"
assert window.print_theme_combo.currentData() == "reference"
assert window.legacy_gbk_check.isChecked()
assert window.options().legacy_gbk
def test_path_rows_and_option_columns_are_aligned(compact_window):
window = compact_window
paths = (window.root_edit, window.output_edit, window.engine_edit)
lefts = [widget.mapTo(window, QPoint()).x() for widget in paths]
assert len(set(lefts)) == 1
assert len({widget.width() for widget in paths}) == 1
assert len({widget.height() for widget in paths}) == 1
buttons = [button for button in window.paths_group.findChildren(QPushButton)
if button.text() in {"选择目录", "选择引擎"}]
assert len(buttons) == 3
assert len({button.width() for button in buttons}) == 1
for first, second in ((window.print_theme_combo, window.color_combo),
(window.font_mapping_combo, window.scope_combo)):
assert first.mapTo(window, QPoint()).x() == second.mapTo(window, QPoint()).x()
assert first.height() == second.height()
for widget in (*paths, window.print_theme_combo, window.font_mapping_combo,
window.scope_combo, window.timeout_spin):
assert window.rect().contains(widget.mapTo(window, widget.rect().bottomRight()))
@pytest.mark.parametrize("kind", ["scan", "batch"])
def test_busy_queue_scrolls_without_checkbox_or_settings_changes(compact_window, project_factory, qtbot, kind):
window = compact_window
for number in range(60):
project_factory(f"board-{number:02d}")
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 60 and not window.busy, timeout=10000)
qtbot.waitUntil(lambda: window.table.verticalScrollBar().maximum() > 0)
before = [window.table.item(row, 0).checkState() for row in range(60)]
window._set_busy(True, kind)
try:
assert window.table.isEnabled()
assert not window.options_group.isEnabled()
assert not window.root_edit.isEnabled()
assert not window.strict_source_check.isEnabled()
assert not window.stroke_check.isEnabled()
scrollbar = window.table.verticalScrollBar()
scrollbar.setFocus()
qtbot.keyClick(scrollbar, Qt.Key_End)
assert scrollbar.maximum() > 0 and scrollbar.value() == scrollbar.maximum()
qtbot.keyClick(scrollbar, Qt.Key_Home)
assert scrollbar.value() == 0
window.table.setCurrentCell(0, 0)
qtbot.mouseClick(window.table.viewport(), Qt.LeftButton,
pos=window.table.visualItemRect(window.table.item(0, 0)).center())
qtbot.keyClick(window.table, Qt.Key_Space)
assert [window.table.item(row, 0).checkState() for row in range(60)] == before
finally:
window._set_busy(False, kind)
assert window.strict_source_check.isEnabled()
assert window.stroke_check.isEnabled()
def test_worker_log_filters_bookkeeping_but_keeps_results_and_errors(compact_window, project_factory, tmp_path, qtbot):
window = compact_window
project_factory()
detail = "字体校验异常:无法读取字体映射"
bookkeeping = (
"核验原工程;直接读取,不创建工程副本或备份",
"原生引擎已启动,PID=1234", "等待原生引擎,已用时 10 秒",
"直接读取原工程;参考配色仅覆盖导出子进程配置,字体修复仅处理输出 PDF",
"字体/配色完成:转换 10 段文字,修复 2 段编码,中文回退 2 段",
"发布前验证 PDF 结构、页数与源工程内容指纹",
f"源工程路径:{tmp_path}",
)
def runner(args, cwd, logs, cancel, timeout, on_event=None, *, env=None):
for message in (*bookkeeping, detail):
on_event(message)
writer = PdfWriter()
writer.add_blank_page(width=500, height=400)
with Path(args[args.index("-a") + 1]).open("wb") as stream:
writer.write(stream)
return 0
window.exporter_factory = lambda engine, runs: Exporter(engine, runs, runner=runner)
engine = tmp_path / "sch2pdf.exe"
engine.write_bytes(b"fake")
window.engine_edit.setText(str(engine))
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 1 and not window.busy, timeout=10000)
window.start_export()
qtbot.waitUntil(lambda: not window.busy, timeout=10000)
text = window.log.toPlainText()
assert not any(message in text for message in bookkeeping)
assert "PID=" not in text and "批量报告:" not in text
assert "扫描" in text and "board" in text and "成功" in text and "队列结束" in text
assert detail in text
assert len(text.splitlines()) <= 8
def test_detailed_failure_reason_stays_in_tooltip_without_growing_layout(compact_window, project_factory, qtbot):
window = compact_window
project_factory()
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 1 and not window.busy, timeout=10000)
height = window.table.height()
detail = "PDF 字体校验失败:缺少字体资源\n" + "缺失对象 123;" * 90
window._item_result(0, ExportResult(project="board", status="failed", message=detail))
window._scan_failed(detail)
qtbot.wait(20)
assert window.table.item(0, 4).toolTip() == detail
assert "缺少字体资源" in window.table.item(0, 4).text()
assert len(window.table.item(0, 4).text()) <= 160
assert window.status_label.toolTip() == detail
assert "字体校验失败" in window.status_label.text()
assert len(window.status_label.text()) <= 160 and "\n" not in window.status_label.text()
assert window.table.height() == height
assert all(len(line) <= 180 for line in window.log.toPlainText().splitlines())
def test_advanced_controls_are_collapsed_and_reachable_without_queue_reset(compact_window, project_factory, qtbot):
window = compact_window
for number in range(45):
project_factory(f"advanced-{number:02d}")
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 45 and not window.busy, timeout=10000)
scrollbar = window.table.verticalScrollBar()
qtbot.waitUntil(lambda: scrollbar.maximum() > 0)
scrollbar.setValue(scrollbar.maximum() // 2)
position = scrollbar.value()
item = window.table.item(25, 0)
assert not window.advanced_panel.isVisible()
assert not window.strict_source_check.isVisible()
qtbot.mouseClick(window.advanced_button, Qt.LeftButton)
qtbot.waitUntil(lambda: window.advanced_panel.isVisible())
assert window.strict_source_check.isVisible() and window.stroke_check.isVisible()
qtbot.mouseClick(window.strict_source_check, Qt.LeftButton)
assert window.options().strict_source
assert window.table.item(25, 0) is item and scrollbar.value() == position
window._set_busy(True)
assert not window.advanced_button.isEnabled()
assert not window.strict_source_check.isEnabled()
window._set_busy(False)
qtbot.mouseClick(window.advanced_button, Qt.LeftButton)
qtbot.waitUntil(lambda: not window.advanced_panel.isVisible())
assert window.options().strict_source
assert window.table.item(25, 0) is item and scrollbar.value() == position
@pytest.mark.parametrize("message", [
"无法写入批量记录:权限不足", "PDF warning: missing glyph", "Unable to read PDF resources",
])
def test_worker_actionable_messages_are_not_filtered(compact_window, message):
compact_window._worker_message(message)
assert message in compact_window.log.toPlainText()
def test_selected_only_retry_passes_full_scanned_list_to_worker(compact_window, project_factory, qtbot, monkeypatch, tmp_path):
from unittest.mock import MagicMock
window = compact_window
for relative, name in (("left/Work", "Work"), ("right/Work", "Work"),
("left/Cert", "Cert"), ("right/Cert", "Cert")):
project_factory(relative, name=name)
window.scan_projects()
qtbot.waitUntil(lambda: window.table.rowCount() == 4 and not window.busy, timeout=10000)
window.table.item(0, 3).setText("失败")
window.select_failed()
assert window.selected_count() == 1
captured = {}
worker = MagicMock()
def make_worker(items, output, options, exporter, parent=None, *, all_projects=None):
captured.update(items=items, all_projects=all_projects, parent=parent)
return worker
monkeypatch.setattr("mentor_pdf_export.ui.BatchWorker", make_worker)
window.exporter_factory = lambda engine, runs: object()
engine = tmp_path / "sch2pdf.exe"
engine.write_bytes(b"fake")
window.engine_edit.setText(str(engine))
window.start_export()
try:
worker.start.assert_called_once()
assert captured["items"] == [(0, window.projects[0])]
assert captured["all_projects"] is window.projects
assert len(captured["all_projects"]) == 4
assert captured["parent"] is window
finally:
window._set_busy(False)
+19
View File
@@ -50,3 +50,22 @@ def test_library_override_preserves_next_project_line(project_factory, tmp_path)
copied=prepare_workspace(source,tmp_path/"run",ExportOptions(library_override=str(library)))
lines=copied.read_text().splitlines()
assert 'KEY DxD_Version "7.9.4"' in lines
def test_empty_library_override_preserves_project_bytes(project_factory,tmp_path):
source=project_factory()
source.write_text(source.read_text()+'KEY CentralLibrary "\\\\server\\library\\original.lmc"\n')
before=source.read_bytes()
copied=prepare_workspace(source,tmp_path/"run",ExportOptions(library_override=""))
assert copied.read_bytes()==before
assert source.read_bytes()==before
def test_compare_fingerprints_reports_sorted_added_removed_and_modified():
from mentor_pdf_export.workspace import compare_fingerprints
before = {"stable": "same", "db/b": "old", "db/a": "old", "deleted": "gone"}
after = {"stable": "same", "db/b": "new", "db/a": "new", "new/z": "z", "new/a": "a"}
assert compare_fingerprints(before, after) == {
"modified": ["db/a", "db/b"], "added": ["new/a", "new/z"], "removed": ["deleted"]
}
assert compare_fingerprints(before, before) == {"modified": [], "added": [], "removed": []}