418 lines
17 KiB
Python
418 lines
17 KiB
Python
"""Testy sidecara dokumentow (abilities/) - bez Dockera i bez Open WebUI.
|
|
|
|
Uruchamiane w obrazie proxy (tests\\runAll.ps1: 'python -m unittest discover
|
|
tests\\py'), ktory NIE ma bibliotek dokumentow - stad skoki: bez python-docx/
|
|
openpyxl/python-pptx test jest SAM POMIJANY, nie udaje, ze cos sprawdzil.
|
|
Na hoscie, gdzie sa zainstalowane, przechodzi pelna runda: create -> plik ->
|
|
walidator formatu -> extract (jesli w PATH jest pandoc) -> token -> TTL.
|
|
|
|
Co jest tu NAPRAWDE sprawdzane, a co nie:
|
|
* spec jest walidowany PRZED rendererem (blad wskazuje pole i dozwolone
|
|
wartosci - na tym stoi samokorekta modelu),
|
|
* wygenerowane pliki sa poprawnymi dokumentami (otwiera je biblioteka
|
|
macierzysta: Worda nie oszukamy plikiem .docx, ktorym nie jest),
|
|
* limit speca i limit pobrania sa wyznaczone przez naglowek, nie przez
|
|
"udane" 200,
|
|
* token HMAC wiaze sie z id i uplywa razem z TTL (plan: ABILITIES_TTL_DNI).
|
|
|
|
Nie sprawdzamy tu LibreOffice (PDF) ani pandoca (extract docx) - to zalezy
|
|
od obrazu, nie od logiki; testy robia to przez pomijanie, nie przez mock.
|
|
"""
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
|
|
# Sciezka do pakietu sidecara (abilities/) - ten plik lezy w tests/py.
|
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "abilities"))
|
|
|
|
from sidecar.config import ustawienia # noqa: E402 (bez zaleznosci: czysty os)
|
|
|
|
# Import reszty przez bronch: bibliotek NIE MA w obrazie proxy (tam skip) ani
|
|
# moga nie byc na hoscie. Klasy poniej sa dekorowane skipUnless - importy
|
|
# wlasnych modurow robia sie w ciele, a nie w liscie importow modulu.
|
|
try:
|
|
from sidecar import store # noqa: F401
|
|
from sidecar.specs import FORMATY, formatuj_bledy # noqa: F401
|
|
from pydantic import ValidationError # noqa: F401
|
|
SDK_LADUJE_SIE = True
|
|
except ImportError:
|
|
SDK_LADUJE_SIE = False
|
|
|
|
BIBLIOTEKI = False
|
|
if SDK_LADUJE_SIE:
|
|
try:
|
|
import io # noqa: F401
|
|
|
|
import docx # noqa: F401
|
|
import openpyxl # noqa: F401
|
|
import pptx # noqa: F401
|
|
BIBLIOTEKI = True
|
|
except ImportError:
|
|
BIBLIOTEKI = False
|
|
|
|
PANDOCA = shutil.which("pandoc") is not None
|
|
|
|
|
|
def _spec_docx():
|
|
return {
|
|
"format": "docx",
|
|
"filename": "umowa.docx",
|
|
"spec": {
|
|
"title": "Umowa dzierzawy nr 1",
|
|
"meta": {"author": "Michal K."},
|
|
"blocks": [
|
|
{"type": "heading", "tekst": "1. Przedmiot", "poziom": 2},
|
|
{"type": "paragraph", "tekst": "Strony **ustalaja**, ze *dzierza* jest placany."},
|
|
{"type": "list", "pozycje": ["a", "b"], "numerowana": True},
|
|
{"type": "list", "pozycje": ["x"], "style_listy": ["number"]},
|
|
{"type": "table", "naglowki": ["A", "B"], "wiersze": [["1", "2"], ["3", "4"]]},
|
|
{"type": "quote", "tekst": "Cytat"},
|
|
{"type": "code", "tekst": "x = 1\ny = 2"},
|
|
{"type": "pagebreak"},
|
|
{"type": "element", "elementy": [
|
|
{"poziom": "h1", "tekst": "Zalacznik",
|
|
"styl": {"kolor": "#1F4E79", "wyrownanie": "center"}},
|
|
{"tekst": "Drobny", "styl": {"rozmiar_pt": 9, "underline": True,
|
|
"wciecie_lewy_cm": 1}},
|
|
]},
|
|
],
|
|
},
|
|
}
|
|
|
|
|
|
@unittest.skipUnless(SDK_LADUJE_SIE, "brak pydantic (obraz proxy bez fastapi) lub bibliotek")
|
|
class TestWalidacjaSpecow(unittest.TestCase):
|
|
|
|
def test_blad_wskazuje_pole_i_dozwolone_wartosci(self):
|
|
with self.assertRaises(ValidationError) as otrzymany:
|
|
FORMATY["docx"](blocks=[{"type": "punkt", "tekst": "x"}])
|
|
komunikaty = formatuj_bledy(otrzymany.exception.errors())
|
|
self.assertEqual(len(komunikaty), 1)
|
|
self.assertIn("blocks[0].type", komunikaty[0])
|
|
# Komunikat MUSI wyliczac dozwolone typy - na tym stoi samokorekta.
|
|
for typ in ("heading", "paragraph", "list", "table", "pagebreak", "element"):
|
|
self.assertIn(typ, komunikaty[0])
|
|
|
|
def test_nieznany_typ_bloku(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["docx"](blocks=[{"type": "zdjecie", "tekst": "x"}])
|
|
|
|
def test_heading_bez_tekstu(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["docx"](blocks=[{"type": "heading"}])
|
|
|
|
def test_list_bez_pozycji(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["docx"](blocks=[{"type": "list"}])
|
|
|
|
def test_style_listy_musi_miec_te_sama_dlugosc(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["docx"](blocks=[{"type": "list", "pozycje": ["a", "b"],
|
|
"style_listy": ["bullet"]}])
|
|
|
|
def test_pole_niedozwolone(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["docx"](bloki=[], title="X") # 'bloki' nie istnieje
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["docx"](blocks=[{"type": "pagebreak", "tekst": "niepotrzebne"}])
|
|
|
|
def test_kolor_musi_byc_rgb(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["docx"](blocks=[{"type": "element", "elementy": [
|
|
{"tekst": "x", "styl": {"kolor": "zielony"}}]}])
|
|
|
|
def test_slajd_bez_tytulu(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["pptx"](slides=[{"bullets": ["a"]}])
|
|
|
|
def test_slajd_blank_bez_tytulu_moze(self):
|
|
spec = FORMATY["pptx"](slides=[{"layout": "blank", "text": "cos"}])
|
|
self.assertEqual(len(spec.slides), 1)
|
|
|
|
def test_formuly_w_xlsx(self):
|
|
spec = FORMATY["xlsx"](sheets=[{"name": "A", "rows": [[1]],
|
|
"formulas": {"C1": "=SUM(A1:B1)"}}])
|
|
self.assertEqual(spec.sheets[0].formulas["C1"], "=SUM(A1:B1)")
|
|
|
|
def test_formula_bez_rowna(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["xlsx"](sheets=[{"rows": [[1]], "formulas": {"C1": "SUM(A1)"}}])
|
|
|
|
def test_nazwy_arkuszy_nie_moga_sie_powtarzac(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["xlsx"](sheets=[{"name": "A"}, {"name": "A"}])
|
|
|
|
def test_dlugi_tekst_odrzucony(self):
|
|
with self.assertRaises(ValidationError):
|
|
FORMATY["docx"](blocks=[{"type": "paragraph", "tekst": "x" * 50_000}])
|
|
|
|
|
|
@unittest.skipUnless(BIBLIOTEKI, "brak python-docx/openpyxl/python-pptx")
|
|
class TestGenerowanie(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self.katalog = tempfile.mkdtemp()
|
|
|
|
def _utworz(self, zadanie):
|
|
from sidecar import render_docx, render_pptx, render_xlsx
|
|
renderery = {"docx": render_docx, "xlsx": render_xlsx, "pptx": render_pptx}
|
|
walidowany = FORMATY[zadanie["format"]].model_validate(zadanie["spec"])
|
|
return renderery[zadanie["format"]].renderuj(walidowany)
|
|
|
|
def test_docx_otwiera_sie_w_python_docx(self):
|
|
import io
|
|
|
|
import docx
|
|
dane = self._utworz(_spec_docx())
|
|
dok = docx.Document(io.BytesIO(dane))
|
|
self.assertGreater(len(dok.paragraphs), 5)
|
|
self.assertEqual(dok.core_properties.author, "Michal K.")
|
|
# naglowek stopnia 2 + akapit + 2 listy + cyt + kod + element(y)
|
|
self.assertEqual(len(dok.tables), 1)
|
|
|
|
def test_tytul_na_pierwszym_akapicie(self):
|
|
import io
|
|
|
|
import docx
|
|
dok = docx.Document(io.BytesIO(self._utworz(_spec_docx())))
|
|
self.assertIn("Umowa", dok.paragraphs[0].text)
|
|
|
|
def test_xlsx_formuly_i_naglowki(self):
|
|
import io
|
|
|
|
import openpyxl
|
|
dane = self._utworz({"format": "xlsx", "spec": {"sheets": [
|
|
{"name": "F", "columns": ["A", "B"], "rows": [[1, 2]],
|
|
"formulas": {"C1": "=A1+B1"}, "freeze_header": True}]}})
|
|
wb = openpyxl.load_workbook(io.BytesIO(dane))
|
|
arkusz = wb["F"]
|
|
self.assertEqual(arkusz["C1"].value, "=A1+B1")
|
|
self.assertEqual(arkusz.freeze_panes, "A2")
|
|
self.assertTrue(arkusz["A1"].font.bold)
|
|
|
|
def test_pptx_slajdy_i_notatki(self):
|
|
import io
|
|
|
|
import pptx
|
|
dane = self._utworz({"format": "pptx", "spec": {
|
|
"title": "Tema", "slides": [
|
|
{"title": "A", "bullets": ["p1", "p2"], "notes": "uwagi"},
|
|
{"layout": "two_col", "title": "B",
|
|
"left_bullets": ["l"], "right_bullets": ["r"]},
|
|
{"layout": "blank", "text": "wolne"}]}})
|
|
prs = pptx.Presentation(io.BytesIO(dane))
|
|
self.assertEqual(len(prs.slides), 4) # slajd otwierajacy + 3
|
|
notatki = prs.slides[1].notes_slide.notes_text_frame.text
|
|
self.assertIn("uwagi", notatki)
|
|
|
|
def test_pusty_xlsx_tez_otwiera_sie(self):
|
|
import io
|
|
|
|
import openpyxl
|
|
dane = self._utworz({"format": "xlsx", "spec": {"sheets": []}})
|
|
wb = openpyxl.load_workbook(io.BytesIO(dane))
|
|
self.assertGreaterEqual(len(wb.sheetnames), 1)
|
|
|
|
# --- estetyka: to generator pilnuje wygladu, nie model -------------------
|
|
|
|
def test_docx_strona_a4(self):
|
|
# Szablon python-docx to Letter - w Polsce (i w kazdym PDF-ie z
|
|
# LibreOffice) karta musi byc A4, takze po obrocie w krajobraz.
|
|
import io
|
|
|
|
import docx
|
|
from docx.shared import Cm
|
|
dok = docx.Document(io.BytesIO(self._utworz(_spec_docx())))
|
|
sekcja = dok.sections[0]
|
|
# delta: zapis do plku obcina wartosci do twipow (1/20 pkt)
|
|
self.assertAlmostEqual(sekcja.page_width, Cm(21.0), delta=1000)
|
|
self.assertAlmostEqual(sekcja.page_height, Cm(29.7), delta=1000)
|
|
|
|
def test_docx_poziomy_a4(self):
|
|
import io
|
|
|
|
import docx
|
|
from docx.shared import Cm
|
|
spec = _spec_docx()
|
|
spec["spec"]["landscape"] = True
|
|
sekcja = docx.Document(io.BytesIO(self._utworz(spec))).sections[0]
|
|
self.assertAlmostEqual(sekcja.page_width, Cm(29.7), delta=1000)
|
|
self.assertAlmostEqual(sekcja.page_height, Cm(21.0), delta=1000)
|
|
|
|
def test_pptx_proporcje_16_9(self):
|
|
# Projektor/ekran w 2026 = 16:9; 4:3 z szablonu dawalo czarne pasy,
|
|
# a pole tekstowe 'blank' (1..12 cali) wykraczalo poza 10-calowy slajd.
|
|
import io
|
|
|
|
import pptx
|
|
from pptx.util import Inches
|
|
prs = pptx.Presentation(io.BytesIO(self._utworz({"format": "pptx", "spec": {
|
|
"title": "T", "slides": [{"layout": "blank", "text": "x"}]}})))
|
|
self.assertEqual(prs.slide_height, Inches(7.5))
|
|
self.assertAlmostEqual(prs.slide_width / prs.slide_height, 16 / 9, places=2)
|
|
|
|
def test_pagebreaki_nie_robia_pustych_stron(self):
|
|
# Poczatkowy, podwojny i koncowy lamaniu = pusta strona w Wordzie/PDF.
|
|
# Model tego nie widzi, wiec generator je usuwa zostawiajac swiadome.
|
|
import io
|
|
|
|
import docx
|
|
dane = self._utworz({"format": "docx", "spec": {"blocks": [
|
|
{"type": "pagebreak"},
|
|
{"type": "paragraph", "tekst": "A"},
|
|
{"type": "pagebreak"},
|
|
{"type": "pagebreak"},
|
|
{"type": "paragraph", "tekst": "B"},
|
|
{"type": "pagebreak"}]}})
|
|
dok = docx.Document(io.BytesIO(dane))
|
|
self.assertEqual(dok.element.xml.count('w:type="page"'), 1)
|
|
|
|
def test_tabela_naglowek_sie_powtarza_wiersz_nie_lamie(self):
|
|
import io
|
|
|
|
import docx
|
|
dane = self._utworz({"format": "docx", "spec": {"blocks": [
|
|
{"type": "table", "naglowki": ["A", "B"], "wiersze": [[1, 2]]}]}})
|
|
xml = docx.Document(io.BytesIO(dane)).element.xml
|
|
self.assertIn("tblHeader", xml)
|
|
self.assertIn("cantSplit", xml)
|
|
self.assertIn("EFEFEF", xml, "szare tlo wiersza naglowkowego")
|
|
|
|
def test_stopka_numer_strony(self):
|
|
import io
|
|
|
|
import docx
|
|
dane = self._utworz(_spec_docx())
|
|
stopka = docx.Document(io.BytesIO(dane)).sections[0].footer
|
|
self.assertIn("PAGE", stopka.paragraphs[0]._p.xml)
|
|
|
|
def test_xlsx_szerokosci_bez_col_widths_i_nadpisanie_z_specem(self):
|
|
import io
|
|
|
|
import openpyxl
|
|
arkusze = {"format": "xlsx", "spec": {"sheets": [
|
|
{"name": "Auto", "columns": ["Imie i nazwisko klienta"], "rows": [["Jan Testowy"]]},
|
|
{"name": "Sztywno", "columns": ["A"], "rows": [["długi tekst na mile"]],
|
|
"col_widths": [6]}]}}
|
|
wb = openpyxl.load_workbook(io.BytesIO(self._utworz(arkusze)))
|
|
self.assertEqual(wb["Auto"].column_dimensions["A"].width, 26.0) # 23 + 3
|
|
self.assertEqual(wb["Sztywno"].column_dimensions["A"].width, 6.0)
|
|
|
|
def test_xlsx_naglowek_zamrozony_domyslnie(self):
|
|
import io
|
|
|
|
import openpyxl
|
|
dane = self._utworz({"format": "xlsx", "spec": {"sheets": [
|
|
{"name": "A", "columns": ["x"], "rows": [[1]]},
|
|
{"name": "B", "columns": ["x"], "rows": [[1]], "freeze_header": False}]}})
|
|
wb = openpyxl.load_workbook(io.BytesIO(dane))
|
|
self.assertEqual(wb["A"].freeze_panes, "A2")
|
|
self.assertIsNone(wb["B"].freeze_panes, "jedyne wyjscie: jawne false")
|
|
|
|
def test_pptx_wielkosc_punktow_dobrana_do_liczby_punktow(self):
|
|
import io
|
|
|
|
import pptx
|
|
from pptx.util import Pt
|
|
dane = self._utworz({"format": "pptx", "spec": {"slides": [
|
|
{"title": "krotkie", "bullets": ["a", "b"]},
|
|
{"title": "dluga lista", "bullets": ["p%d" % i for i in range(1, 10)]}]}})
|
|
prs = pptx.Presentation(io.BytesIO(dane))
|
|
rozmiary = []
|
|
for slajd in prs.slides:
|
|
for ksztalt in slajd.shapes:
|
|
if not ksztalt.has_text_frame:
|
|
continue
|
|
paragrafy = ksztalt.text_frame.paragraphs
|
|
if len(paragrafy) > 1 and paragrafy[0].runs:
|
|
rozmiary.append(paragrafy[0].runs[0].font.size)
|
|
self.assertEqual(rozmiary, [Pt(20), Pt(13)])
|
|
|
|
|
|
@unittest.skipUnless(BIBLIOTEKI and PANDOCA, "brak pandoca")
|
|
class TestRoundTrip(unittest.TestCase):
|
|
"""create -> extract zwraca tresc zgodna ze specem (kryterium akceptacji)."""
|
|
|
|
def test_docx_przez_pandoca(self):
|
|
from sidecar import extract, render_docx
|
|
spec = FORMATY["docx"].model_validate(_spec_docx()["spec"])
|
|
dane = render_docx.renderuj(spec)
|
|
tekst = extract.ekstrakcja(dane, "dokument.docx")
|
|
for fragment in ("Umowa dzierzawy nr 1", "1. Przedmiot", "ustalaja",
|
|
"Cytat", "x = 1"):
|
|
self.assertIn(fragment, tekst)
|
|
|
|
def test_pptx_przez_pandoca(self):
|
|
from sidecar import extract, render_pptx
|
|
spec = FORMATY["pptx"].model_validate({"title": "Tema", "slides": [
|
|
{"title": "Pierwszy", "bullets": ["ala"]}]})
|
|
dane = render_pptx.renderuj(spec)
|
|
tekst = extract.ekstrakcja(dane, "prez.pptx")
|
|
self.assertIn("Pierwszy", tekst)
|
|
self.assertIn("ala", tekst)
|
|
|
|
|
|
@unittest.skipUnless(SDK_LADUJE_SIE, "brak pydantic/bibliotek dokumentow")
|
|
class TestSklepPlikow(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self.katalog = tempfile.mkdtemp()
|
|
self.stary_secret = ustawienia.secret
|
|
self.stary_ttl = ustawienia.ttl_dni
|
|
ustawienia.secret = "sekret-testowy"
|
|
ustawienia.ttl_dni = 7
|
|
|
|
def tearDown(self):
|
|
ustawienia.secret = self.stary_secret
|
|
ustawienia.ttl_dni = self.stary_ttl
|
|
|
|
def test_nazwa_sanowana(self):
|
|
self.assertEqual(store.sanuj_nazwe("../../etc/passwd", "x"), "etc_passwd")
|
|
self.assertEqual(store.sanuj_nazwe("", "x"), "x")
|
|
self.assertNotIn("/", store.sanuj_nazwe("a/b\\c"))
|
|
|
|
def test_dodaj_i_znajdz(self):
|
|
wpis = store.dodaj_plik(self.katalog, b"abc", "Raport.docx", "docx")
|
|
znaleziono, sciezka = store.znajdz(self.katalog, wpis["id"])
|
|
self.assertEqual(znaleziono["nazwa"], "Raport.docx")
|
|
self.assertTrue(sciezka.is_file())
|
|
self.assertIn(wpis["id"], sciezka.name)
|
|
|
|
def test_token_wiaze_sie_z_id(self):
|
|
token = store.token("id-1")
|
|
self.assertFalse(store.token_wazny("id-2", token))
|
|
self.assertTrue(store.token_wazny("id-1", token))
|
|
|
|
def test_bez_sekretu_brak_waznych_tokenow(self):
|
|
ustawienia.secret = ""
|
|
self.assertFalse(store.token_wazny("id", "dowolny"))
|
|
|
|
def test_ttl_usuwa_przestarzale(self):
|
|
wpis = store.dodaj_plik(self.katalog, b"abc", "a.txt", "txt")
|
|
self.assertEqual(store.usun_przestarzale(self.katalog), 0)
|
|
# przestawiamy waznosc w przeszlosc i sprzatamy
|
|
import json
|
|
indeks_plik = os.path.join(self.katalog, "indeks.json")
|
|
with open(indeks_plik, encoding="utf-8") as u:
|
|
indeks = json.load(u)
|
|
indeks[wpis["id"]]["wazny_do"] = int(time.time()) - 10
|
|
with open(indeks_plik, "w", encoding="utf-8") as u:
|
|
json.dump(indeks, u)
|
|
self.assertEqual(store.usun_przestarzale(self.katalog), 1)
|
|
wpis2, _ = store.znajdz(self.katalog, wpis["id"])
|
|
self.assertIsNone(wpis2)
|
|
|
|
|
|
class TestLimity(unittest.TestCase):
|
|
|
|
def test_max_spec_ustawiony(self):
|
|
self.assertEqual(ustawienia.max_spec_bytes, 256 * 1024)
|
|
self.assertEqual(ustawienia.max_extract_chars, 40_000)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|