64 lines
2.2 KiB
Python
64 lines
2.2 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Конвертация .doc через Word COM: без Word — внятная подсказка; temp-файлы чистятся."""
|
||
import io
|
||
import os
|
||
from types import SimpleNamespace
|
||
|
||
import pytest
|
||
|
||
import app
|
||
|
||
|
||
def _fake_run_factory(returncode=0, creates_dst=True):
|
||
"""Подмена subprocess.run: PowerShell 'конвертировал' — dst существует."""
|
||
calls = []
|
||
|
||
def fake_run(argv, timeout, capture_output):
|
||
calls.append((argv[-1], timeout))
|
||
if creates_dst:
|
||
dst = argv[-1].split("SaveAs2('", 1)[-1].split("'")[0]
|
||
open(dst, "wb").write(b"PK\x03\x04 fake-docx")
|
||
return SimpleNamespace(returncode=returncode)
|
||
return fake_run, calls
|
||
|
||
|
||
def test_doc_converted_and_temp_cleaned(monkeypatch):
|
||
import subprocess
|
||
fake_run, calls = _fake_run_factory()
|
||
monkeypatch.setattr(subprocess, "run", fake_run)
|
||
out = app.doc_to_docx_bytes(b"fake-doc-bytes")
|
||
assert out.startswith(b"PK")
|
||
assert len(calls) == 1 and calls[0][1] == 90
|
||
argv = calls[0][0]
|
||
# пути переданы: исходник с .doc, цель с .docx (SaveAs2 формат 16)
|
||
assert ".doc'" in argv and "SaveAs2('" in argv
|
||
dst = argv.split("SaveAs2('", 1)[-1].split("'")[0]
|
||
assert not os.path.exists(dst) # temp-файл удалён
|
||
|
||
|
||
def test_doc_without_word(monkeypatch):
|
||
import subprocess
|
||
fake_run, _ = _fake_run_factory(returncode=1, creates_dst=False)
|
||
monkeypatch.setattr(subprocess, "run", fake_run)
|
||
with pytest.raises(ValueError, match="пересохраните документ как .docx"):
|
||
app.doc_to_docx_bytes(b"broken")
|
||
|
||
|
||
def test_extract_paragraphs_doc_routes_through_converter(monkeypatch):
|
||
from docx import Document
|
||
doc = Document()
|
||
doc.add_paragraph("Первый абзац.")
|
||
doc.add_paragraph("Второй абзац.")
|
||
buf = io.BytesIO()
|
||
doc.save(buf)
|
||
seen = {}
|
||
|
||
def fake_convert(data):
|
||
seen["bytes"] = data
|
||
return buf.getvalue()
|
||
|
||
monkeypatch.setattr(app, "doc_to_docx_bytes", fake_convert)
|
||
paras = app.extract_paragraphs(b"whatever", "otchet.doc")
|
||
assert paras == ["Первый абзац.", "Второй абзац."]
|
||
assert seen["bytes"] == b"whatever"
|