Files
MDHelper/tests/test_content_revision_057.py

112 lines
5.7 KiB
Python

"""Commit-boundary conflicts and preservation of list content in Word."""
import zipfile
from lxml import etree as ET
import pytest
from mdhelper import file_versions as files, batch_documents as batch, rename_references as rename
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.markdown_renderer import MarkdownRenderer
from mdhelper.docx_style import W, NS
from test_style_regressions import parts
TABLE_LIST = '1. | HeadOne | HeadTwo |\n |---|---|\n | CellOne | CellTwo |\n\n ContinuedText\n\n2. LastText'
HEADING_LIST = '1. ### FirstHeading\n\n ContinuedText\n\n2. ### LastHeading'
@pytest.mark.parametrize('operation', ['batch', 'rename'])
@pytest.mark.parametrize('boundary', ['flush', 'replace'])
def test_transactions_retain_external_save_at_commit(tmp_path, monkeypatch, operation, boundary):
target = tmp_path/'ref.md'
target.write_bytes(b'[Link](old.md)')
stage = tmp_path/'stage'; stage.write_bytes(b'Exported')
source = tmp_path/'old.md'; source.write_bytes(b'Source')
plan = rename.plan_rename(tmp_path, source, tmp_path/'new.md')
expected = {target: files.fingerprint(target)}
replace, fsync = files._replace_with_backup, files.os.fsync
external = b'External save at final commit boundary'
injected = False
def race_replace(temporary, path, backup):
nonlocal injected
if path == target and not injected:
injected = True; target.write_bytes(external)
replace(temporary, path, backup)
def race_flush(descriptor):
nonlocal injected
fsync(descriptor)
if not injected:
injected = True; target.write_bytes(external)
monkeypatch.setattr(files, '_replace_with_backup', race_replace) if boundary == 'replace' else monkeypatch.setattr(files.os, 'fsync', race_flush)
with pytest.raises(OSError):
if operation == 'batch': batch.publish_outputs({target: stage}, expected, tmp_path)
else: rename.execute_rename(plan, tmp_path/'backups')
assert target.read_bytes() == external
assert source.exists() and not (tmp_path/'new.md').exists()
def test_creation_does_not_overwrite_file_created_at_commit(tmp_path, monkeypatch):
path = tmp_path/'new.out'
operation = 'rename' if files.os.name == 'nt' else 'link'
publish = getattr(files.os, operation)
def race(src, dst):
path.write_bytes(b'External creation')
publish(src, dst)
monkeypatch.setattr(files.os, operation, race)
with pytest.raises(FileExistsError): files.atomic_write(path, b'Export', expected=None)
assert path.read_bytes() == b'External creation'
@pytest.mark.skipif(files.os.name != 'nt', reason='Windows exclusive rename')
def test_new_output_does_not_require_hardlinks(tmp_path, monkeypatch):
def unsupported(*args): raise OSError('Hard links are not supported on this volume')
monkeypatch.setattr(files.os, 'link', unsupported)
path=tmp_path/'new.out'
files.atomic_write(path,b'Exported',expected=None)
assert path.read_bytes()==b'Exported'
def test_second_conflict_during_recovery_keeps_both_external_versions(tmp_path, monkeypatch):
path = tmp_path/'existing.out'; path.write_bytes(b'Original')
expected = files.fingerprint(path)
replace = files._replace_with_backup
count = 0
def racing_replace(temporary, target, backup):
nonlocal count
count += 1; path.write_bytes(f'External {count}'.encode())
replace(temporary, target, backup)
monkeypatch.setattr(files, '_replace_with_backup', racing_replace)
with pytest.raises(OSError, match='恢复副本'): files.atomic_write(path, b'Export', expected=expected)
recovered = [p.read_bytes() for p in tmp_path.iterdir()]
assert b'External 1' in recovered and b'External 2' in recovered
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
def test_table_first_list_preserves_cells_and_numbered_empty_paragraph(tmp_path, engine):
path = export_markdown_to_docx(TABLE_LIST, tmp_path/'table.docx', engine=engine)
doc, _ = parts(path)
body = doc.find(W+'body'); table = body.find(W+'tbl')
assert [''.join(c.itertext()) for c in table.findall('w:tr/w:tc', NS)] == ['HeadOne','HeadTwo','CellOne','CellTwo']
before = table.getprevious()
assert before.tag == W+'p' and before.find('w:pPr/w:numPr', NS) is not None
continued = next(p for p in doc.iter(W+'p') if ''.join(p.itertext()) == 'ContinuedText')
num = continued.find('w:pPr/w:numPr/w:numId', NS)
if num is not None:
with zipfile.ZipFile(path) as package: numbering = ET.fromstring(package.read('word/numbering.xml'))
abstract = numbering.find(f"w:num[@w:numId='{num.get(W+'val')}']/w:abstractNumId", NS).get(W+'val')
marker = numbering.find(f"w:abstractNum[@w:abstractNumId='{abstract}']/w:lvl/w:lvlText", NS).get(W+'val')
assert not marker.strip()
assert '\u200b' not in ''.join(doc.itertext())
@pytest.mark.parametrize('prefix', ['1. ', '- ', '> 1. ', '1. > '])
def test_combined_heading_preserves_container_prefix(tmp_path, prefix):
source = prefix + '### Heading\n'
combined = batch.combine_documents([batch.BatchDocument(tmp_path/'one.md', source)], MarkdownRenderer(tmp_path))
assert prefix + '#### Heading {#mdh1h1}' in combined.word_source
def test_combined_word_keeps_heading_numbering(tmp_path):
combined = batch.combine_documents([batch.BatchDocument(tmp_path/'one.md', HEADING_LIST)], MarkdownRenderer(tmp_path))
doc, _ = parts(export_markdown_to_docx(combined.word_source, tmp_path/'combined.docx', engine='pandoc'))
headings = [p for p in doc.iter(W+'p') if ''.join(p.itertext()) in ('FirstHeading', 'LastHeading')]
assert len(headings) == 2
assert all(p.find('w:pPr/w:numPr', NS) is not None for p in headings)