Files
auto-stock/backend/tests/test_dt_scheduler_alert_tasks_r3.py
shuim a264561576 fix: 하드닝 루프 8회차 — 체결 보정·고아 감지·청산 경보·실시간/차트·리스크 가드 일괄 수정
- 스윙 체결가 확인 전 executed_price NULL + fill_sweep, 진입가 resolve(ActiveTrade↔Portfolio), 0체결/부분체결 매수 장부 원복
- DT 고아 감지(근거 한정)·0체결 매도 복원·stale 점검 확대, 시간손절 -0.3% 원복
- 폴백 손절 ATR 캐시, 거래량부족-차단 신호 매수 차단, 현금 5% 유보 재적용, MDD peak/reset 수정
- KIS 서킷브레이커 청산 우회·경보, db_worker 재큐잉 순서, heartbeat·health-watch 사이드카
- 실시간 WS 재구독·41건 우선순위·다건 프레임 분할, 차트 샘플 제거·당일봉 합성, WS 서브프로토콜 인증
- 프론트: 미관리 그룹·확인 모달·차트 실시간 반영·예수금 표시 정정
- 전문가 에이전트 6종 추가(.claude/agents)
- 유닛 스위트 2667 passed (소켓 차단 하), tsc OK

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y83Za98XsNw9zuA4FTUytN
2026-10-10 12:17:49 +09:00

99 lines
3.3 KiB
Python

"""[하드닝 R3] DT 청산 연속 실패 경보 태스크 — 강참조 보관·타임아웃·실패 로그.
목은 공통 종단(telegram_notifier.notify_system_warning)에 건다. 실패 경로는 예외 발생형.
"""
import asyncio
import gc
import logging
import pytest
from app.services.daytrading import scheduler as dts
from app.services.telegram_notifier import TelegramNotifier
class _SendBoom(Exception):
pass
@pytest.fixture(autouse=True)
def _reset():
dts._alert_tasks.clear()
dts._dt_exit_health["consecutive_failures"] = 0
dts._dt_exit_health["last_error"] = None
yield
dts._alert_tasks.clear()
@pytest.mark.asyncio
async def test_alert_task_strongly_referenced_until_done(monkeypatch):
gate = asyncio.Event()
sent = []
async def _fake(self, category, message):
await gate.wait()
sent.append((category, message))
monkeypatch.setattr(TelegramNotifier, "notify_system_warning", _fake)
dts._notify_dt_warning_bg_v2("hello")
assert len(dts._alert_tasks) == 1
gc.collect()
assert len(dts._alert_tasks) == 1 # GC 후에도 참조 유지
gate.set()
for _ in range(5):
await asyncio.sleep(0)
assert sent == [("DAYTRADING", "hello")]
assert len(dts._alert_tasks) == 0 # 완료 후 제거
@pytest.mark.asyncio
async def test_alert_via_exit_failure_threshold(monkeypatch):
sent = []
async def _fake(self, category, message):
sent.append(message)
monkeypatch.setattr(TelegramNotifier, "notify_system_warning", _fake)
for _ in range(dts.DT_EXIT_FAILURE_ALERT_THRESHOLD):
dts._record_dt_exit_result_v2(False, "timeout")
assert len(dts._alert_tasks) == 1
await asyncio.gather(*list(dts._alert_tasks))
await asyncio.sleep(0)
assert len(sent) == 1 and "timeout" in sent[0]
assert not dts._alert_tasks
@pytest.mark.asyncio
async def test_alert_send_exception_logged_error(monkeypatch, caplog):
async def _boom(self, category, message):
raise _SendBoom("telegram down")
monkeypatch.setattr(TelegramNotifier, "notify_system_warning", _boom)
with caplog.at_level(logging.ERROR, logger=dts.logger.name):
dts._notify_dt_warning_bg_v2("msg-x")
await asyncio.gather(*list(dts._alert_tasks))
assert any("경보 텔레그램 실패" in r.message and "msg-x" in r.message
and r.levelno == logging.ERROR for r in caplog.records)
await asyncio.sleep(0)
assert not dts._alert_tasks
@pytest.mark.asyncio
async def test_alert_send_timeout_logged_error(monkeypatch, caplog):
async def _hang(self, category, message):
await asyncio.sleep(3600)
monkeypatch.setattr(TelegramNotifier, "notify_system_warning", _hang)
monkeypatch.setattr(dts, "DT_ALERT_SEND_TIMEOUT_SEC", 0.05)
with caplog.at_level(logging.ERROR, logger=dts.logger.name):
dts._notify_dt_warning_bg_v2("msg-t")
await asyncio.wait_for(asyncio.gather(*list(dts._alert_tasks)), timeout=2.0)
assert any("초과" in r.message and "msg-t" in r.message for r in caplog.records)
def test_alert_without_running_loop_does_not_raise(caplog):
with caplog.at_level(logging.ERROR, logger=dts.logger.name):
dts._notify_dt_warning_bg_v2("no-loop")
assert any("경보 태스크 생성 실패" in r.message for r in caplog.records)
assert not dts._alert_tasks