224 lines
6.7 KiB
Python
224 lines
6.7 KiB
Python
"""Testy sekce správy úložiště /admin/uloziste a úklidu osiřelých souborů."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import sqlite3
|
|
from io import BytesIO
|
|
from pathlib import Path
|
|
|
|
from flask import Flask
|
|
from flask.testing import FlaskClient
|
|
from PIL import Image
|
|
|
|
from poznavacky import admin_sets, storage
|
|
from poznavacky.security import hash_password
|
|
|
|
_CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"')
|
|
|
|
|
|
def _csrf(client: FlaskClient, path: str) -> str:
|
|
resp = client.get(path)
|
|
assert resp.status_code == 200
|
|
match = _CSRF_RE.search(resp.get_data(as_text=True))
|
|
assert match is not None
|
|
return match.group(1)
|
|
|
|
|
|
def _insert_user(
|
|
db: sqlite3.Connection,
|
|
*,
|
|
email: str,
|
|
password: str,
|
|
role: str,
|
|
) -> int:
|
|
cur = db.execute(
|
|
"""
|
|
INSERT INTO uzivatele (
|
|
email, heslo_hash, jmeno, prijmeni, role, stav
|
|
) VALUES (?, ?, 'Jana', 'Testova', ?, 'schvaleny')
|
|
""",
|
|
(email, hash_password(password), role),
|
|
)
|
|
db.commit()
|
|
assert cur.lastrowid is not None
|
|
return int(cur.lastrowid)
|
|
|
|
|
|
def _login(client: FlaskClient, email: str, password: str) -> None:
|
|
token = _csrf(client, "/prihlaseni")
|
|
resp = client.post(
|
|
"/prihlaseni",
|
|
data={"csrf_token": token, "email": email, "heslo": password},
|
|
)
|
|
assert resp.status_code == 302
|
|
|
|
|
|
def _make_img(size: tuple[int, int] = (500, 400)) -> bytes:
|
|
buf = BytesIO()
|
|
Image.new("RGB", size, (180, 90, 30)).save(buf, format="PNG")
|
|
return buf.getvalue()
|
|
|
|
|
|
def test_storage_page_access_control(
|
|
client: FlaskClient,
|
|
db: sqlite3.Connection,
|
|
) -> None:
|
|
_insert_user(db, email="zak@example.test", password="heslo-zak", role="zak")
|
|
_insert_user(
|
|
db,
|
|
email="ucitelka@example.test",
|
|
password="heslo-ucitelka",
|
|
role="ucitelka",
|
|
)
|
|
|
|
assert client.get("/admin/uloziste").status_code == 302
|
|
_login(client, "zak@example.test", "heslo-zak")
|
|
assert client.get("/admin/uloziste").status_code == 403
|
|
|
|
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
|
assert client.get("/admin/uloziste").status_code == 200
|
|
assert client.post("/admin/uloziste/uklid-sirotku").status_code == 403
|
|
|
|
|
|
def test_storage_overview_sorting_set_deletion_and_orphan_cleanup(
|
|
app: Flask,
|
|
client: FlaskClient,
|
|
db: sqlite3.Connection,
|
|
) -> None:
|
|
_insert_user(
|
|
db,
|
|
email="ucitelka@example.test",
|
|
password="heslo-ucitelka",
|
|
role="ucitelka",
|
|
)
|
|
zak_id = _insert_user(
|
|
db,
|
|
email="zak@example.test",
|
|
password="heslo-zak",
|
|
role="zak",
|
|
)
|
|
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
|
|
|
# Sada A (větší, 2 položky, 3 fotky, 1 odehrané kolo) a prázdná sada B.
|
|
cur_a = db.execute(
|
|
"""
|
|
INSERT INTO sady (slug, nazev, stav)
|
|
VALUES ('zvire-sada', 'Zvířata', 'publikovano')
|
|
"""
|
|
)
|
|
sada_a = int(cur_a.lastrowid)
|
|
cur_a1 = db.execute(
|
|
"INSERT INTO polozky (sada_id, nazev) VALUES (?, 'Liška')",
|
|
(sada_a,),
|
|
)
|
|
item_a1 = int(cur_a1.lastrowid)
|
|
cur_a2 = db.execute(
|
|
"INSERT INTO polozky (sada_id, nazev) VALUES (?, 'Vlk')",
|
|
(sada_a,),
|
|
)
|
|
item_a2 = int(cur_a2.lastrowid)
|
|
db.execute(
|
|
"""
|
|
INSERT INTO kola (uzivatel_id, sada_id, rezim, typ_kola, pocet_otazek)
|
|
VALUES (?, ?, 'psani', 'cele', 2)
|
|
""",
|
|
(zak_id, sada_a),
|
|
)
|
|
|
|
cur_b = db.execute(
|
|
"""
|
|
INSERT INTO sady (slug, nazev, stav)
|
|
VALUES ('alpha-prazdna', 'Alpha prázdná', 'koncept')
|
|
"""
|
|
)
|
|
sada_b = int(cur_b.lastrowid)
|
|
db.commit()
|
|
|
|
media_dir = Path(app.config["MEDIA_DIR"])
|
|
_, p1 = admin_sets.save_photo_for_item(
|
|
db, media_dir, sada_a, item_a1, _make_img((900, 600))
|
|
)
|
|
admin_sets.save_photo_for_item(
|
|
db, media_dir, sada_a, item_a1, _make_img((800, 600))
|
|
)
|
|
admin_sets.save_photo_for_item(
|
|
db, media_dir, sada_a, item_a2, _make_img((700, 500))
|
|
)
|
|
|
|
# Vytvoříme dva osiřelé soubory.
|
|
orphan_in_set = media_dir / str(sada_a) / "sirotek_v_sade.webp"
|
|
orphan_in_set.write_bytes(b"o" * 400)
|
|
orphan_dir = media_dir / "99"
|
|
orphan_dir.mkdir()
|
|
orphan_foreign = orphan_dir / "zapomenuta.webp"
|
|
orphan_foreign.write_bytes(b"z" * 600)
|
|
|
|
# Výchozí zobrazení: metrika médií, DB, volné místo, rozbalitelný seznam
|
|
# sirotků, sada A před sadou B a varování na odehraná kola.
|
|
resp = client.get("/admin/uloziste")
|
|
assert resp.status_code == 200
|
|
html = resp.get_data(as_text=True)
|
|
assert "99/zapomenuta.webp" in html
|
|
assert f"{sada_a}/sirotek_v_sade.webp" in html
|
|
assert "0,00 MB" in html
|
|
assert "odehraných kol" in html
|
|
assert html.index("Zvířata") < html.index("Alpha prázdná")
|
|
|
|
# Řazení podle názvu vzestupně -> Alpha prázdná před Zvířata.
|
|
sorted_html = client.get("/admin/uloziste?sort=name&dir=asc").get_data(
|
|
as_text=True
|
|
)
|
|
assert sorted_html.index("Alpha prázdná") < sorted_html.index("Zvířata")
|
|
|
|
# Úklid sirotků smaže jen oba sirotky a cizí prázdný adresář 99.
|
|
token = _csrf(client, "/admin/uloziste")
|
|
clean_resp = client.post(
|
|
"/admin/uloziste/uklid-sirotku",
|
|
data={"csrf_token": token},
|
|
follow_redirects=True,
|
|
)
|
|
assert clean_resp.status_code == 200
|
|
assert "Uklizeno 2 osiřelých souborů" in clean_resp.get_data(as_text=True)
|
|
assert not orphan_in_set.exists()
|
|
assert not orphan_foreign.exists()
|
|
assert not orphan_dir.exists()
|
|
assert (media_dir / p1.soubor_plny).is_file()
|
|
assert media_dir.is_dir()
|
|
|
|
# Opakovaný úklid je idempotentní.
|
|
clean_again = client.post(
|
|
"/admin/uloziste/uklid-sirotku",
|
|
data={"csrf_token": token},
|
|
follow_redirects=True,
|
|
)
|
|
assert "Nebyly nalezeny žádné osiřelé soubory" in clean_again.get_data(
|
|
as_text=True
|
|
)
|
|
|
|
# Odolnost proti chybějícímu souboru + okamžité uvolnění místa při smazání.
|
|
(media_dir / p1.soubor_plny).unlink()
|
|
bytes_before, _ = storage.scan_media_dir(
|
|
media_dir,
|
|
storage.get_referenced_media_paths(db),
|
|
)
|
|
assert bytes_before > 0
|
|
|
|
del_resp = client.post(
|
|
f"/admin/sady/{sada_a}/smazat",
|
|
data={"csrf_token": token, "next": "/admin/uloziste"},
|
|
follow_redirects=True,
|
|
)
|
|
assert del_resp.status_code == 200
|
|
assert not (media_dir / str(sada_a)).exists()
|
|
bytes_after, _ = storage.scan_media_dir(
|
|
media_dir,
|
|
storage.get_referenced_media_paths(db),
|
|
)
|
|
assert bytes_after == 0
|
|
sada_b_row = db.execute(
|
|
"SELECT id FROM sady WHERE id = ?",
|
|
(sada_b,),
|
|
).fetchone()
|
|
assert sada_b_row is not None
|