58 lines
2.8 KiB
Python
58 lines
2.8 KiB
Python
import http.client
|
|
import os
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
import zipfile
|
|
from datetime import datetime, timezone
|
|
from io import BytesIO
|
|
from pathlib import Path
|
|
|
|
from app.belki.admin_filters import WEB_TIMEZONE, matches_period, period_bounds
|
|
from app.belki.xlsx_export import build_xlsx
|
|
from app.main import BelkiHTTPServer, Handler
|
|
|
|
|
|
class AdminFilterAndExportTests(unittest.TestCase):
|
|
def test_named_and_custom_periods_filter_records(self) -> None:
|
|
now = datetime(2026, 9, 1, 12, tzinfo=timezone.utc)
|
|
recent = {"created_at": "2026-09-01T11:30:00+00:00"}
|
|
old = {"created_at": "2026-08-30T11:30:00+00:00"}
|
|
self.assertTrue(matches_period(recent, *period_bounds("2h", None, None, now=now)))
|
|
self.assertFalse(matches_period(old, *period_bounds("2h", None, None, now=now)))
|
|
self.assertTrue(matches_period(old, *period_bounds("all", "2026-08-30", "2026-08-30", now=now)))
|
|
start, _ = period_bounds("all", "2026-08-30", "2026-08-30", now=now)
|
|
self.assertEqual(start, datetime(2026, 8, 29, 21, tzinfo=timezone.utc))
|
|
|
|
def test_xlsx_is_a_valid_workbook_with_filters_and_typed_values(self) -> None:
|
|
content = build_xlsx(sheet_name="Отчёты", headers=["ID", "Создан", "Текст"], rows=[[7, datetime(2026, 9, 1, 12, 30, tzinfo=timezone.utc), "Только выбранная строка"]], display_timezone=WEB_TIMEZONE)
|
|
with zipfile.ZipFile(BytesIO(content)) as archive:
|
|
self.assertTrue(archive.testzip() is None)
|
|
sheet = archive.read("xl/worksheets/sheet1.xml").decode()
|
|
self.assertIn("Только выбранная строка", sheet)
|
|
self.assertIn('autoFilter ref="A1:C2"', sheet)
|
|
self.assertIn('s="2"', sheet)
|
|
|
|
def test_xlsx_routes_require_admin_authorization(self) -> None:
|
|
prior = os.environ.get("BELKI_ADMIN_PASSWORD")
|
|
os.environ["BELKI_ADMIN_PASSWORD"] = "test-password"
|
|
server = BelkiHTTPServer(("127.0.0.1", 0), Handler)
|
|
worker = threading.Thread(target=server.serve_forever, daemon=True)
|
|
worker.start()
|
|
try:
|
|
for path in ("/api/admin/calculations.xlsx", "/api/admin/applications.xlsx"):
|
|
connection = http.client.HTTPConnection("127.0.0.1", server.server_port)
|
|
connection.request("GET", path)
|
|
response = connection.getresponse()
|
|
self.assertEqual(response.status, 401)
|
|
response.read()
|
|
connection.close()
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
worker.join(timeout=2)
|
|
if prior is None:
|
|
del os.environ["BELKI_ADMIN_PASSWORD"]
|
|
else:
|
|
os.environ["BELKI_ADMIN_PASSWORD"] = prior
|