Files
trumpsignal-backend/tests/test_user_hl_api_key.py
T
k 5fb1d52026 Pre-launch hardening: KOL module, Telegram, scanners, WS resilience
Big-picture changes since b941223:

KOL pipeline (new) — Substack/podcast/blog RSS → AI ticker extraction →
on-chain wallet diff → talks-vs-trades divergence detection. Daily polls,
19 feeds, divergence emits Post + Telegram fan-out.

Telegram push (new) — walletless free tier + wallet-linked Pro upgrade,
in-bot preference commands (/trump /btc /funding /kol /conf /quiet),
signed-envelope API for dashboard. Disconnect-wallet keeps free
subscription.

BTC funding-rate reversal scanner (new) — hourly cron, 30d cumulative
funding threshold + mean-revert + 7d price confirm, emits via
/api/signals/ingest. BTC bottom-reversal scanner promoted to System 2.

WS broadcast rewrite — per-client send timeout + parallel fan-out
(asyncio.gather). Fixes "Binance WS no close frame" reconnect storms +
APScheduler 11-min job misses, both caused by one slow client stalling
the kline loop.

Error visibility — three silent-error sites (trumpstruth/truth_social
fetchers, funding_reversal scanner) now include exception type name so
httpx ConnectError-style empty-message errors stop logging blank lines.
Telegram bot loop now classifies ReadTimeout vs network vs unknown +
logger.exception for the unknown bucket.

Security hygiene — trumpsignal.db untracked from git (held subscriber
wallets + encrypted HL keys + 22 bot trades); .gitignore now blocks
*.db/.next/backups. CORS only allows FRONTEND_URL in production.

New ops scripts —
  - scripts/preflight.py: env/DB/Telegram/AI auth verification gate
  - scripts/backup_db.sh: cron-friendly daily DB backup (SQLite + Postgres)
  - scripts/seed_kol_wallets.py: idempotent KOL on-chain wallet seeder

15 new Alembic migrations (007-021) covering convex strategy fields,
phase-1 safety, two-system frozen exits, invalidation prices, dynamic
SYS2 leverage, staged de-risk + pyramiding, peak gain tracking, risk
mode, auto-trade + grow flags, KOL module, KOL on-chain, KOL divergence,
Telegram bindings + walletless.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 00:52:56 +08:00

84 lines
2.0 KiB
Python

import pytest
from fastapi import HTTPException
from app.api import user
def _make_sub():
class Sub:
wallet_address = "0xabc"
hl_api_key = None
return Sub()
class _Scalar:
def __init__(self, value):
self._value = value
def scalar_one_or_none(self):
return self._value
class _Db:
def __init__(self, sub):
self.sub = sub
self.committed = False
async def execute(self, _stmt):
return _Scalar(self.sub)
async def commit(self):
self.committed = True
class _Body:
wallet = "0xabc"
timestamp = 123
signature = "0xsig"
api_key = "0x" + "1" * 64
@pytest.mark.asyncio
async def test_set_hl_api_key_saves_only_after_hyperliquid_verification(monkeypatch):
sub = _make_sub()
db = _Db(sub)
monkeypatch.setattr(user, "verify_signed_request", lambda **_kwargs: None)
monkeypatch.setattr(user, "encrypt_api_key", lambda value: f"encrypted:{value[-6:]}")
calls = []
async def verify_key(**kwargs):
calls.append(kwargs)
monkeypatch.setattr(user, "verify_hl_api_key_can_trade", verify_key)
result = await user.set_hl_api_key("0xabc", _Body(), db)
assert db.committed is True
assert sub.hl_api_key == "encrypted:111111"
assert result.status == "ok"
assert result.verified is True
assert calls == [{"api_key": _Body.api_key, "account_address": "0xabc"}]
@pytest.mark.asyncio
async def test_set_hl_api_key_does_not_save_when_hyperliquid_verification_fails(monkeypatch):
sub = _make_sub()
db = _Db(sub)
monkeypatch.setattr(user, "verify_signed_request", lambda **_kwargs: None)
async def fail_verify(**_kwargs):
raise HTTPException(422, "Hyperliquid rejected this API key")
monkeypatch.setattr(user, "verify_hl_api_key_can_trade", fail_verify)
with pytest.raises(HTTPException) as exc:
await user.set_hl_api_key("0xabc", _Body(), db)
assert exc.value.status_code == 422
assert db.committed is False
assert sub.hl_api_key is None