修复 lint 警告及测试 monkeypatch 引用

This commit is contained in:
2569718930@qq.com
2026-06-16 02:03:47 +08:00
parent dca4f2d618
commit 6d7f213cd9
11 changed files with 31 additions and 31 deletions
+18 -12
View File
@@ -10,12 +10,9 @@ Usage:
from __future__ import annotations from __future__ import annotations
import json
import math import math
import os import os
import random import random
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
import torch import torch
import torch.nn as nn import torch.nn as nn
@@ -237,8 +234,9 @@ def predict(model, forecasts, city, mv, cv):
if __name__ == "__main__": if __name__ == "__main__":
import sys, statistics import sys
from src.analysis.deb_algorithm import load_history as lh, get_deb_accuracy, calculate_dynamic_weights import statistics
from src.analysis.deb_algorithm import load_history as lh, calculate_dynamic_weights
from src.data_collection.city_registry import CITY_REGISTRY from src.data_collection.city_registry import CITY_REGISTRY
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -255,20 +253,28 @@ if __name__ == "__main__":
print("No checkpoint. Run --train first.") print("No checkpoint. Run --train first.")
sys.exit(1) sys.exit(1)
m, mv, cv = load_model(ckpt) m, mv, cv = load_model(ckpt)
base, attn_errs = [], [] base: list = []
attn_errs: list = []
for city in [c for c in CITY_REGISTRY if c in history]: for city in [c for c in CITY_REGISTRY if c in history]:
cd = history.get(city, {}) cd = history.get(city, {})
for d in sorted(cd.keys(), reverse=True)[:5]: for d in sorted(cd.keys(), reverse=True)[:5]:
rec = cd[d]; fc = rec.get("forecasts", {}); actual = rec.get("actual_high") rec = cd[d]
if not fc or actual is None: continue fc = rec.get("forecasts", {})
actual = rec.get("actual_high")
if not fc or actual is None:
continue
try: try:
bp, _ = calculate_dynamic_weights(city, fc) bp, _ = calculate_dynamic_weights(city, fc)
if bp: base.append(abs(bp - float(actual))) if bp:
except: pass base.append(abs(bp - float(actual)))
except Exception:
pass
try: try:
ap, _ = predict(m, fc, city, mv, cv) ap, _ = predict(m, fc, city, mv, cv)
if ap: attn_errs.append(abs(ap - float(actual))) if ap:
except: pass attn_errs.append(abs(ap - float(actual)))
except Exception:
pass
if base and attn_errs: if base and attn_errs:
print(f"Baseline MAE: {statistics.mean(base):.3f}") print(f"Baseline MAE: {statistics.mean(base):.3f}")
print(f"Attention MAE: {statistics.mean(attn_errs):.3f}") print(f"Attention MAE: {statistics.mean(attn_errs):.3f}")
-1
View File
@@ -95,7 +95,6 @@ class MetarSourceMixin:
return None return None
cache_key = f"{icao}:{utc_offset}:{use_fahrenheit}" cache_key = f"{icao}:{utc_offset}:{use_fahrenheit}"
now_ts = time.time()
cache_ttl_sec = self._metar_cache_ttl_for_city(city, icao) cache_ttl_sec = self._metar_cache_ttl_for_city(city, icao)
cached = self.cache.get_ttl("metar", cache_key, cache_ttl_sec) cached = self.cache.get_ttl("metar", cache_key, cache_ttl_sec)
if cached is not None: if cached is not None:
+1 -1
View File
@@ -8,7 +8,7 @@ from __future__ import annotations
import threading import threading
import time import time
from typing import Any, Callable, Dict, Optional from typing import Any, Dict, Optional
class WeatherCacheManager: class WeatherCacheManager:
-1
View File
@@ -10,7 +10,6 @@ from datetime import datetime, timedelta, timezone
from typing import Optional, Dict, Any, List, Set, Tuple from typing import Optional, Dict, Any, List, Set, Tuple
from urllib.parse import urlparse from urllib.parse import urlparse
import requests
from loguru import logger from loguru import logger
from src.database.sqlite_connection import connect_sqlite from src.database.sqlite_connection import connect_sqlite
-1
View File
@@ -1,4 +1,3 @@
import sqlite3
from datetime import datetime, timezone from datetime import datetime, timezone
from src.database.db_manager import DBManager from src.database.db_manager import DBManager
+3 -2
View File
@@ -1,3 +1,4 @@
import src.auth.supabase_admin_client as admin_client_module
from types import SimpleNamespace from types import SimpleNamespace
import src.database.db_manager as db_manager_module import src.database.db_manager as db_manager_module
@@ -41,7 +42,7 @@ def test_message_points_sync_to_supabase_metadata_is_throttled(tmp_path, monkeyp
raising=False, raising=False,
) )
monkeypatch.setattr( monkeypatch.setattr(
db_manager_module.requests, admin_client_module.requests,
"patch", "patch",
lambda *args, **kwargs: calls.append((args, kwargs)) lambda *args, **kwargs: calls.append((args, kwargs))
or SimpleNamespace(status_code=204, text="", content=b""), or SimpleNamespace(status_code=204, text="", content=b""),
@@ -78,7 +79,7 @@ def test_manual_point_grant_forces_supabase_metadata_sync(tmp_path, monkeypatch)
raising=False, raising=False,
) )
monkeypatch.setattr( monkeypatch.setattr(
db_manager_module.requests, admin_client_module.requests,
"patch", "patch",
lambda *args, **kwargs: calls.append((args, kwargs)) lambda *args, **kwargs: calls.append((args, kwargs))
or SimpleNamespace(status_code=204, text="", content=b""), or SimpleNamespace(status_code=204, text="", content=b""),
+3 -2
View File
@@ -2,6 +2,7 @@ from types import SimpleNamespace
import src.database.db_manager as db_manager_module import src.database.db_manager as db_manager_module
from src.database.db_manager import DBManager from src.database.db_manager import DBManager
import src.auth.supabase_admin_client as admin_client_module
def _bound_db(tmp_path, monkeypatch): def _bound_db(tmp_path, monkeypatch):
@@ -43,7 +44,7 @@ def test_repeated_user_upsert_coalesces_supabase_profile_sync(tmp_path, monkeypa
raising=False, raising=False,
) )
monkeypatch.setattr( monkeypatch.setattr(
db_manager_module.requests, admin_client_module.requests,
"patch", "patch",
lambda *args, **kwargs: calls.append((args, kwargs)) lambda *args, **kwargs: calls.append((args, kwargs))
or SimpleNamespace(status_code=204, text="", content=b""), or SimpleNamespace(status_code=204, text="", content=b""),
@@ -69,7 +70,7 @@ def test_changed_username_bypasses_supabase_profile_sync_coalescing(tmp_path, mo
raising=False, raising=False,
) )
monkeypatch.setattr( monkeypatch.setattr(
db_manager_module.requests, admin_client_module.requests,
"patch", "patch",
lambda *args, **kwargs: calls.append((args, kwargs)) lambda *args, **kwargs: calls.append((args, kwargs))
or SimpleNamespace(status_code=204, text="", content=b""), or SimpleNamespace(status_code=204, text="", content=b""),
-2
View File
@@ -86,7 +86,6 @@ def _bind_optional_supabase_identity(request: Request) -> None:
def _resolve_auth_points(request: Request, account_db=None) -> int: def _resolve_auth_points(request: Request, account_db=None) -> int:
from src.database.db_manager import DBManager
if account_db is None: if account_db is None:
# imported lazily to avoid circular dependency at module level # imported lazily to avoid circular dependency at module level
@@ -127,7 +126,6 @@ def _resolve_auth_points(request: Request, account_db=None) -> int:
def _resolve_weekly_profile(request: Request, account_db=None) -> Dict[str, Any]: def _resolve_weekly_profile(request: Request, account_db=None) -> Dict[str, Any]:
from src.database.db_manager import DBManager
if account_db is None: if account_db is None:
from web.core import _account_db as _db from web.core import _account_db as _db
+2 -3
View File
@@ -11,7 +11,6 @@ from typing import Any, Dict, List, Optional
import requests as _requests import requests as _requests
from fastapi import HTTPException, Request from fastapi import HTTPException, Request
from src.database.db_manager import DBManager # type hints
from src.utils.runtime_secrets import get_runtime_secret_status from src.utils.runtime_secrets import get_runtime_secret_status
@@ -276,7 +275,7 @@ def grant_ops_subscription(
deduct_points: int = 0, deduct_points: int = 0,
) -> dict[str, Any]: ) -> dict[str, Any]:
_require_ops(request) _require_ops(request)
from datetime import datetime, timedelta from datetime import datetime
import web.routes as legacy_routes # lazy avoid circular import import web.routes as legacy_routes # lazy avoid circular import
@@ -359,7 +358,7 @@ def extend_ops_subscription(
additional_days: int = 30, additional_days: int = 30,
) -> dict[str, Any]: ) -> dict[str, Any]:
_require_ops(request) _require_ops(request)
from datetime import datetime, timedelta from datetime import datetime
import web.routes as legacy_routes # lazy avoid circular import import web.routes as legacy_routes # lazy avoid circular import
-1
View File
@@ -7,7 +7,6 @@ from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
from fastapi import HTTPException, Request from fastapi import HTTPException, Request
import requests as _requests
from src.database.db_manager import DBManager # type hints from src.database.db_manager import DBManager # type hints
import web.routes as legacy_routes import web.routes as legacy_routes
+4 -5
View File
@@ -30,7 +30,7 @@ def _require_ops(request):
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Users / Points / Feedback / Analytics # Users / Points / Feedback / Analytics
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
from web.services.ops.users import ( # noqa: F401 from web.services.ops.users import ( # noqa: E402, F401
get_ops_analytics_funnel, get_ops_analytics_funnel,
get_ops_weekly_leaderboard, get_ops_weekly_leaderboard,
grant_ops_feedback_reward, grant_ops_feedback_reward,
@@ -44,7 +44,7 @@ from web.services.ops.users import ( # noqa: F401
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Payments / Billing / Memberships # Payments / Billing / Memberships
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
from web.services.ops.payments import ( # noqa: F401 from web.services.ops.payments import ( # noqa: E402, F401
get_ops_billing_risk, get_ops_billing_risk,
get_ops_memberships_growth, get_ops_memberships_growth,
get_ops_memberships_overview, get_ops_memberships_overview,
@@ -57,7 +57,7 @@ from web.services.ops.payments import ( # noqa: F401
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Health / Source Health / Training / Truth # Health / Source Health / Training / Truth
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
from web.services.ops.health import ( # noqa: F401 from web.services.ops.health import ( # noqa: E402, F401
_build_training_accuracy_payload, _build_training_accuracy_payload,
get_ops_health_check, get_ops_health_check,
get_ops_observation_collector_status, get_ops_observation_collector_status,
@@ -69,8 +69,7 @@ from web.services.ops.health import ( # noqa: F401
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Config / Subscriptions / Logs / Telegram # Config / Subscriptions / Logs / Telegram
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
from web.services.ops.config import ( # noqa: F401 from web.services.ops.config import ( # noqa: E402, F401
_lookup_supabase_user_id_by_email,
_supabase_rest_rows, _supabase_rest_rows,
extend_ops_subscription, extend_ops_subscription,
get_ops_config, get_ops_config,