feat: 只保留管理入口,缓存小区信息表解析,连接中显示提示,移除脚本管理打包方式

This commit is contained in:
2026-11-12 11:53:12 +08:00
parent 5bcf5cfa89
commit 1c5c32bfdc
19 changed files with 317 additions and 457 deletions
+74 -3
View File
@@ -6,6 +6,7 @@ import io
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
@@ -22,6 +23,7 @@ import main
from etl_app import auth, connectors, worker
from etl_app.config import Settings, SettingsError, SettingsStore, public_view, validate
from etl_app.data import DataBrowser, DataQuery, cell, difference, where_clause
from etl_app.i18n import MESSAGES
from etl_app.runner import Runner, parse_output
from etl_app.runs import RunStore
from etl_app.scheduler import EtlScheduler
@@ -212,6 +214,24 @@ class RunnerTest(unittest.TestCase):
time.sleep(0.05)
self.assertEqual(self.runs.latest_finished()["status"], "cancelled")
def test_run_that_cannot_start_is_recorded_as_failed(self) -> None:
with mock.patch.object(self.runner, "_execute", side_effect=OSError("disk full")):
with self.assertRaises(OSError):
self.runner.run("manual")
row = self.runs.latest_finished()
assert row is not None
self.assertEqual((row["status"], row["detail"]), ("failed", "OSError: disk full"))
self.assertFalse(self.runner.busy())
def test_worker_receives_the_cell_data_cache_directory(self) -> None:
self.mode_file.write_text("processed", encoding="utf-8")
with mock.patch("etl_app.runner.subprocess.Popen", wraps=subprocess.Popen) as popen:
self.runner.run("manual")
command = popen.call_args.args[0]
self.assertEqual(command[command.index("--cache") + 1], str(Path(self.temp.name) / "cache" / "cell-data"))
def test_prune_keeps_latest_outputs(self) -> None:
output = Path(self.temp.name) / "output"
for name in ("20260731090000", "20260731100000", ".20260731110000.tmp-1"):
@@ -242,6 +262,11 @@ class SchedulerTest(unittest.TestCase):
scheduler.shutdown()
class TranslationTest(unittest.TestCase):
def test_both_languages_define_the_same_keys(self) -> None:
self.assertEqual(set(MESSAGES["zh"]), set(MESSAGES["en"]))
class AuthTest(unittest.TestCase):
def test_identity_requires_matching_proxy_token(self) -> None:
headers = {
@@ -271,7 +296,8 @@ class ApiTest(unittest.TestCase):
):
service = EtlService(Path(temp))
with TestClient(build_api(service)) as client:
self.assertEqual(client.get("/").status_code, 200)
root = client.get("/", follow_redirects=False)
self.assertEqual((root.status_code, root.headers["location"]), (307, "admin"))
self.assertEqual(client.get("/api/status").status_code, 401)
member = {"x-metrix-proxy-token": "secret", "x-metrix-app-role": "user"}
self.assertEqual(client.get("/api/status", headers=member).status_code, 403)
@@ -685,19 +711,64 @@ class WorkerTest(unittest.TestCase):
(root / "history").mkdir()
settings_path = Path(temp) / "settings.json"
SettingsStore(settings_path).update(
complete_settings(source_root="/source", history_root="/history", lookback_days=3)
complete_settings(source_root="/source", history_root="/history", lookback_days=3, history_keep_days=0)
)
store = RecordingStore()
cache = Path(temp) / "cache"
output = io.StringIO()
with mock.patch.object(worker, "build_storage", return_value=LocalFileStorage(root)), mock.patch.object(
worker, "build_store", return_value=store
), contextlib.redirect_stdout(output):
self.assertEqual(worker.run(settings_path, Path(temp) / "output", dry_run=False), 0)
self.assertEqual(worker.run(settings_path, Path(temp) / "output", dry_run=False, cache_dir=cache), 0)
self.assertIn("status=processed", output.getvalue())
# The five test workbooks have identical bytes: one is parsed, the others reuse its entry.
self.assertIn("4 read from cache", output.getvalue())
self.assertEqual(len(store.rows), 2)
archived = list((root / "history" / "2026-07-31").iterdir())
self.assertEqual(len(archived), 1)
self.assertEqual(len(list(cache.iterdir())), 1)
def test_history_retention_runs_only_after_a_group_is_stored(self) -> None:
with tempfile.TemporaryDirectory() as temp:
root = Path(temp) / "remote"
for source_type in main.EXPECTED_TYPES:
create_archive(root / "source", source_type, COMPLETE_WINDOW)
create_cell_data_sources(root)
expired = root / "history" / "2020-01-01"
expired.mkdir(parents=True)
settings_path = Path(temp) / "settings.json"
SettingsStore(settings_path).update(
complete_settings(source_root="/source", history_root="/history", history_keep_days=7)
)
def run(store: RecordingStore, dry_run: bool = False) -> str:
output = io.StringIO()
with mock.patch.object(worker, "build_storage", return_value=LocalFileStorage(root)), mock.patch.object(
worker, "build_store", return_value=store
), contextlib.redirect_stdout(output):
worker.run(settings_path, Path(temp) / "output", dry_run=dry_run)
return output.getvalue()
self.assertIn("status=processed", run(RecordingStore(), dry_run=True))
self.assertIn("status=skipped", run(RecordingStore(datetime(2026, 8, 1))))
self.assertTrue(expired.exists())
stored = run(RecordingStore())
self.assertIn("status=processed", stored)
self.assertIn("history_removed=/history/2020-01-01", stored)
self.assertFalse(expired.exists())
def test_failed_history_retention_keeps_the_run_successful(self) -> None:
settings = Settings(history_keep_days=7)
output = io.StringIO()
with mock.patch.object(main.StorageHistoryStore, "prune", side_effect=OSError("connection lost")), contextlib.redirect_stdout(
output
):
worker.prune_history(mock.Mock(), settings)
self.assertEqual(output.getvalue(), "history_prune_error=OSError: connection lost\n")
def test_dry_run_skips_database_and_history(self) -> None:
with tempfile.TemporaryDirectory() as temp:
+47 -1
View File
@@ -7,6 +7,7 @@ import json
from pathlib import Path
import tempfile
import unittest
from unittest import mock
import zipfile
import main
@@ -226,6 +227,51 @@ class PipelineTest(unittest.TestCase):
self.assertEqual(metadata["460-00-200-1"], ("113.123456", "22.654321", "0"))
def test_cell_data_cache_parses_each_workbook_content_once(self) -> None:
first = create_cell_data_workbook(longitude=113.1)
changed = create_cell_data_workbook(longitude=113.2)
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp) / "cache"
expected = main.parse_cell_data_workbook(first, "cell-data.xlsx")
cold = main.CellDataCache(directory)
self.assertEqual(main.load_cell_metadata([("cell-data.xlsx", first)], cold), expected)
self.assertEqual(cold.hits, 0)
self.assertEqual(len(list(directory.iterdir())), 1)
warm = main.CellDataCache(directory)
with mock.patch.object(main, "parse_cell_data_workbook", side_effect=AssertionError("parsed again")):
self.assertEqual(main.load_cell_metadata([("renamed.xlsx", first)], warm), expected)
self.assertEqual(warm.hits, 1)
updated = main.CellDataCache(directory)
metadata = main.load_cell_metadata([("cell-data.xlsx", changed)], updated)
self.assertEqual(metadata["460-00-200-1"][0], "113.2")
self.assertEqual(updated.hits, 0)
self.assertEqual(len(list(directory.iterdir())), 1)
def test_damaged_cell_data_cache_entry_is_parsed_again(self) -> None:
raw = create_cell_data_workbook()
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp)
main.load_cell_metadata([("cell-data.xlsx", raw)], main.CellDataCache(directory))
(entry,) = directory.iterdir()
for damaged in ("{not json", '{"460-00-200-1": ["113.1"]}', "[]"):
entry.write_text(damaged, encoding="utf-8")
cache = main.CellDataCache(directory)
metadata = main.load_cell_metadata([("cell-data.xlsx", raw)], cache)
self.assertEqual(metadata["460-00-200-1"], ("113.123456", "22.654321", "30"))
self.assertEqual(cache.hits, 0)
def test_invalid_cell_data_workbook_is_not_cached(self) -> None:
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp) / "cache"
with self.assertRaisesRegex(main.ProcessingError, "Invalid CellData workbook"):
main.load_cell_metadata([("bad.xlsx", b"not a workbook")], main.CellDataCache(directory))
self.assertFalse(directory.exists())
def test_nearby_count_uses_high_interference_rows_with_coordinates(self) -> None:
rows = [
nearby_row("a", "113.000000", "22.000000", "2.6G"),
@@ -400,7 +446,7 @@ class PipelineTest(unittest.TestCase):
def test_api_history_store_creates_date_directory_and_uploads_csv(self) -> None:
client = FakeHistoryApiClient()
history = main.ApiHistoryStore(client, "stg_test", "/history")
history = main.StorageHistoryStore(main.MetrixStorage(client, "stg_test"), "/history")
metric_time = datetime(2026, 8, 6, 12, 0)
self.assertFalse(history.exists(metric_time))