import io import json import tempfile import zipfile from pathlib import Path from app.config_upload import install_config_files, normalize_json, validate_xlsx def _minimal_xlsx() -> bytes: buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as archive: archive.writestr("[Content_Types].xml", "") archive.writestr("xl/workbook.xml", "") return buffer.getvalue() def test_validate_xlsx_accepts_workbook_zip(): assert validate_xlsx(_minimal_xlsx()) == _minimal_xlsx() def test_validate_xlsx_rejects_arbitrary_pk_data(): try: validate_xlsx(b"PK-not-a-real-xlsx") except ValueError as exc: assert "XLSX" in str(exc) else: raise AssertionError("invalid XLSX was accepted") def test_normalize_json_rejects_scalar_and_formats_object(): assert json.loads(normalize_json(b'{"a":1}')) == {"a": 1} try: normalize_json(b'"scalar"') except ValueError as exc: assert "object" in str(exc) else: raise AssertionError("scalar JSON was accepted") def test_install_config_files_replaces_and_backs_up_existing_file(): with tempfile.TemporaryDirectory() as directory: root = Path(directory) target = root / "rules.json" target.write_bytes(b"old") install_config_files(root, [("rules.json", b"new")]) assert target.read_bytes() == b"new" assert (root / "rules.json.bak").read_bytes() == b"old"