[AI]
Фикс создания файла
This commit is contained in:
@@ -42,7 +42,7 @@ def create_gost_example():
|
||||
import shutil
|
||||
shutil.rmtree(doc_dir.parent, ignore_errors=True)
|
||||
|
||||
def test_gost_example_document_not_empty(create_gost_example):
|
||||
def test_gost_example_document_is_not_empty(create_gost_example):
|
||||
input_dir = create_gost_example
|
||||
|
||||
process_document(
|
||||
@@ -54,11 +54,100 @@ def test_gost_example_document_not_empty(create_gost_example):
|
||||
output_path = Path("tests/output/gost_example.docx")
|
||||
assert output_path.exists(), "Файл .docx не создан"
|
||||
|
||||
# Открываем и проверяем, что в документе есть хотя бы 1 параграф
|
||||
# Открываем и проверяем, что в документе есть хотя бы 1 непустой параграф
|
||||
doc = Document(output_path)
|
||||
assert len(doc.paragraphs) > 0, "Документ пустой (нет параграфов)"
|
||||
assert len(doc.tables) >= 0, "Документ не содержит таблиц (это нормально)"
|
||||
assert any(p.text.strip() != "" for p in doc.paragraphs), "Все параграфы пустые"
|
||||
|
||||
# Проверяем, что есть хотя бы 1 параграф
|
||||
assert len(doc.paragraphs) > 0, f"Документ пустой: {len(doc.paragraphs)} параграфов"
|
||||
|
||||
# Проверяем, что хотя бы один параграф **не пустой**
|
||||
non_empty_paragraphs = [p for p in doc.paragraphs if p.text.strip() != ""]
|
||||
assert len(non_empty_paragraphs) > 0, f"Все параграфы пустые: {[p.text for p in doc.paragraphs]}"
|
||||
|
||||
# Проверяем, что есть хотя бы один заголовок "ВВЕДЕНИЕ"
|
||||
found_intro = any("ВВЕДЕНИЕ" in p.text for p in doc.paragraphs)
|
||||
assert found_intro, f"Заголовок 'ВВЕДЕНИЕ' не найден. Параграфы: {[p.text for p in doc.paragraphs]}"
|
||||
|
||||
# Проверяем, что есть текст "Текст введения"
|
||||
found_intro_text = any("Текст введения" in p.text for p in doc.paragraphs)
|
||||
assert found_intro_text, f"Текст 'Текст введения' не найден. Параграфы: {[p.text for p in doc.paragraphs]}"
|
||||
|
||||
# Удаляем после теста
|
||||
output_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def test_gost_example_document_content(create_gost_example):
|
||||
input_dir = create_gost_example
|
||||
|
||||
process_document(
|
||||
input_dir=input_dir,
|
||||
output_dir=Path("tests/output"),
|
||||
style_config_path=Path("resources/themes/gost.yaml"),
|
||||
)
|
||||
|
||||
output_path = Path("tests/output/gost_example.docx")
|
||||
assert output_path.exists(), "Файл .docx не создан"
|
||||
|
||||
doc = Document(output_path)
|
||||
|
||||
# Проверим, что есть хотя бы 2 параграфа (заголовок + текст)
|
||||
assert len(doc.paragraphs) >= 2, f"Документ содержит только {len(doc.paragraphs)} параграфов"
|
||||
|
||||
# Проверим, что в параграфах есть нужный текст
|
||||
texts = [p.text for p in doc.paragraphs]
|
||||
assert "ВВЕДЕНИЕ" in texts, "Заголовок 'ВВЕДЕНИЕ' не найден"
|
||||
assert "Текст введения." in texts, "Текст введения не найден"
|
||||
assert "Текст актуальности." in texts, "Текст актуальности не найден"
|
||||
|
||||
# Проверим, что таблица добавлена
|
||||
assert len(doc.tables) >= 1, "Таблица не найдена в документе"
|
||||
|
||||
# Проверим, что в таблице есть нужные данные
|
||||
table = doc.tables[0]
|
||||
assert table.cell(0, 0).text == "Показатель"
|
||||
assert table.cell(0, 1).text == "2022" # заголовок
|
||||
assert table.cell(1, 0).text == "Выручка"
|
||||
assert table.cell(1, 1).text == "1000" # тело таблицы
|
||||
|
||||
# Удаляем после теста
|
||||
output_path.unlink(missing_ok=True)
|
||||
|
||||
def test_gost_example_document_is_not_empty_debug(create_gost_example):
|
||||
input_dir = create_gost_example
|
||||
|
||||
process_document(
|
||||
input_dir=input_dir,
|
||||
output_dir=Path("tests/output"),
|
||||
style_config_path=Path("resources/themes/gost.yaml"),
|
||||
)
|
||||
|
||||
output_path = Path("tests/output/gost_example.docx")
|
||||
assert output_path.exists(), "Файл .docx не создан"
|
||||
|
||||
# Открываем и проверяем, что в документе есть хотя бы 1 непустой параграф
|
||||
doc = Document(output_path)
|
||||
|
||||
print(f"Количество параграфов: {len(doc.paragraphs)}")
|
||||
for i, p in enumerate(doc.paragraphs):
|
||||
print(f"Параграф {i}: '{p.text}' (len={len(p.text)})")
|
||||
print(f" Количество runs: {len(p.runs)}")
|
||||
for j, run in enumerate(p.runs):
|
||||
print(f" Run {j}: '{run.text}' (len={len(run.text)})")
|
||||
|
||||
# Проверяем, что есть хотя бы 1 параграф
|
||||
assert len(doc.paragraphs) > 0, f"Документ пустой: {len(doc.paragraphs)} параграфов"
|
||||
|
||||
# Проверяем, что хотя бы один параграф **не пустой**
|
||||
non_empty_paragraphs = [p for p in doc.paragraphs if p.text.strip() != ""]
|
||||
assert len(non_empty_paragraphs) > 0, f"Все параграфы пустые: {[p.text for p in doc.paragraphs]}"
|
||||
|
||||
# Проверяем, что есть хотя бы один заголовок "ВВЕДЕНИЕ"
|
||||
found_intro = any("ВВЕДЕНИЕ" in p.text for p in doc.paragraphs)
|
||||
assert found_intro, f"Заголовок 'ВВЕДЕНИЕ' не найден. Параграфы: {[p.text for p in doc.paragraphs]}"
|
||||
|
||||
# Проверяем, что есть текст "Текст введения"
|
||||
found_intro_text = any("Текст введения" in p.text for p in doc.paragraphs)
|
||||
assert found_intro_text, f"Текст 'Текст введения' не найден. Параграфы: {[p.text for p in doc.paragraphs]}"
|
||||
|
||||
# Удаляем после теста
|
||||
output_path.unlink(missing_ok=True)
|
||||
@@ -28,7 +28,7 @@ def test_handle_image():
|
||||
doc = Document()
|
||||
style_reg = StyleRegistry(Path("resources/style_config.yaml"))
|
||||
style_reg.ensure_styles_in_doc(doc)
|
||||
node = {"type": "image", "src": "images/logo.png", "alt": "Логотип"} # ✅ src = images/logo.png
|
||||
node = {"type": "image", "src": "images/logo.png", "alt": "Логотип"}
|
||||
|
||||
# Создаем реальное изображение
|
||||
img_path = Path("tests/fixtures/images/logo.png")
|
||||
@@ -36,7 +36,8 @@ def test_handle_image():
|
||||
img = Image.new("RGB", (100, 100), color="red")
|
||||
img.save(img_path)
|
||||
|
||||
handle_image(node, doc, Path("tests/fixtures"), style_reg) # images_dir = tests/fixtures
|
||||
# images_dir должен указывать на папку images/
|
||||
handle_image(node, doc, Path("tests/fixtures/images"), style_reg)
|
||||
|
||||
# После вызова должно быть 2 параграфа: картинка и подпись
|
||||
assert len(doc.paragraphs) == 2
|
||||
@@ -93,18 +94,23 @@ def test_handle_table():
|
||||
node = {
|
||||
"type": "table",
|
||||
"children": [
|
||||
{ # header
|
||||
"type": "table_row",
|
||||
{ # table_head
|
||||
"type": "table_head",
|
||||
"children": [
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Заголовок 1"}]},
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Заголовок 2"}]},
|
||||
]
|
||||
},
|
||||
{ # row 1
|
||||
"type": "table_row",
|
||||
{ # table_body
|
||||
"type": "table_body",
|
||||
"children": [
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Ячейка 1"}]},
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Ячейка 2"}]},
|
||||
{ # table_row
|
||||
"type": "table_row",
|
||||
"children": [
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Ячейка 1"}]},
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Ячейка 2"}]},
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -124,22 +130,32 @@ def test_handle_table_with_br():
|
||||
node = {
|
||||
"type": "table",
|
||||
"children": [
|
||||
{ # header
|
||||
"type": "table_row",
|
||||
{ # table_head
|
||||
"type": "table_head",
|
||||
"children": [
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Заголовок 1"}]},
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Заголовок 2"}]},
|
||||
{ # table_row
|
||||
"type": "table_row",
|
||||
"children": [
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Заголовок 1"}]},
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Заголовок 2"}]},
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{ # row 1
|
||||
"type": "table_row",
|
||||
{ # table_body
|
||||
"type": "table_body",
|
||||
"children": [
|
||||
{"type": "table_cell", "children": [
|
||||
{"type": "text", "raw": "Первая строка"},
|
||||
{"type": "softbreak"}, # или linebreak/html
|
||||
{"type": "text", "raw": "Вторая строка"}
|
||||
]},
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Ячейка 2"}]},
|
||||
{ # row 1
|
||||
"type": "table_row",
|
||||
"children": [
|
||||
{"type": "table_cell", "children": [
|
||||
{"type": "text", "raw": "Первая строка"},
|
||||
{"type": "softbreak"}, # или linebreak/html
|
||||
{"type": "text", "raw": "Вторая строка"}
|
||||
]},
|
||||
{"type": "table_cell", "children": [{"type": "text", "raw": "Ячейка 2"}]},
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
53
tests/test_real_cli_call.py
Normal file
53
tests/test_real_cli_call.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
def test_real_cli_call_creates_non_empty_doc():
|
||||
import tempfile
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
tmp_path = Path(tmp_dir)
|
||||
input_dir = tmp_path / "inputs"
|
||||
output_dir = tmp_path / "outputs"
|
||||
input_dir.mkdir()
|
||||
output_dir.mkdir()
|
||||
|
||||
# Создаём папку example_doc
|
||||
doc_dir = input_dir / "example_doc"
|
||||
doc_dir.mkdir()
|
||||
(doc_dir / "document.md").write_text("# ВВЕДЕНИЕ\n\nТекст введения.", encoding="utf-8")
|
||||
(doc_dir / "images").mkdir()
|
||||
|
||||
# Запускаем CLI через subprocess
|
||||
result = subprocess.run([
|
||||
sys.executable, "-m", "src",
|
||||
"--input", str(input_dir),
|
||||
"--output", str(output_dir),
|
||||
"--style", "resources/style_config.yaml"
|
||||
], capture_output=True, text=True, cwd=Path(__file__).parent.parent) # запускаем из корня проекта
|
||||
|
||||
print("STDOUT:", result.stdout)
|
||||
print("STDERR:", result.stderr)
|
||||
print("Return code:", result.returncode)
|
||||
|
||||
assert result.returncode == 0, f"CLI завершился с ошибкой: {result.stderr}"
|
||||
|
||||
# Проверяем, что файл создан
|
||||
output_path = output_dir / "example_doc.docx"
|
||||
assert output_path.exists(), "Файл .docx не создан через CLI"
|
||||
|
||||
# Открываем и проверяем
|
||||
from docx import Document
|
||||
doc = Document(output_path)
|
||||
|
||||
print(f"Real CLI: Количество параграфов: {len(doc.paragraphs)}")
|
||||
for i, p in enumerate(doc.paragraphs):
|
||||
print(f"Real CLI: Параграф {i}: '{p.text}' (len={len(p.text)})")
|
||||
|
||||
# Проверяем, что есть хотя бы 1 непустой параграф
|
||||
non_empty_paragraphs = [p for p in doc.paragraphs if p.text.strip() != ""]
|
||||
assert len(non_empty_paragraphs) > 0, f"Real CLI: Все параграфы пустые: {[p.text for p in doc.paragraphs]}"
|
||||
|
||||
# Проверяем, что есть заголовок
|
||||
found_intro = any("ВВЕДЕНИЕ" in p.text for p in doc.paragraphs)
|
||||
assert found_intro, f"Real CLI: Заголовок 'ВВЕДЕНИЕ' не найден"
|
||||
Reference in New Issue
Block a user