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
This commit is contained in:
122
backend/tests/test_portfolio_v2_pending_r7.py
Normal file
122
backend/tests/test_portfolio_v2_pending_r7.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""portfolio_v2 /buy·/sell: 접수≠체결, 결과 불명 처리 (manual_buy R3 정합)."""
|
||||
import pytest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from app.api.endpoints import portfolio_v2 as v2
|
||||
from app.api.endpoints.manual_buy import BuyRequest
|
||||
from app.api.endpoints.portfolio import SellRequest
|
||||
from fastapi import HTTPException
|
||||
from app.core.config import settings
|
||||
|
||||
CODE = "005930"
|
||||
|
||||
|
||||
class _Res:
|
||||
def __init__(self, v):
|
||||
self._v = v
|
||||
|
||||
def scalar_one_or_none(self):
|
||||
return self._v
|
||||
|
||||
def scalar(self):
|
||||
return 0
|
||||
|
||||
def scalars(self):
|
||||
return SimpleNamespace(all=lambda: [])
|
||||
|
||||
|
||||
def _ctx():
|
||||
return SimpleNamespace(
|
||||
user_id=1, is_legacy=False,
|
||||
kis=SimpleNamespace(get_current_price=AsyncMock(return_value={"output": {
|
||||
"stck_prpr": str(settings.MIN_PRICE_KRW + 50000), "hts_kor_isnm": "T"}})),
|
||||
loss_tracker=SimpleNamespace(is_banned_safe=AsyncMock(return_value=False),
|
||||
record_trade_result_safe=AsyncMock(), save_to_db_v2=AsyncMock()),
|
||||
mdd=SimpleNamespace(can_open_new_position=AsyncMock(return_value=True)),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cap(monkeypatch):
|
||||
th = []
|
||||
|
||||
async def _eth(p):
|
||||
th.append(p)
|
||||
|
||||
pf = AsyncMock()
|
||||
monkeypatch.setattr(v2, "enqueue_trade_history", _eth)
|
||||
monkeypatch.setattr(v2, "enqueue_portfolio_upsert", pf)
|
||||
monkeypatch.setattr(v2, "_last_done_v2", {})
|
||||
# 예외 발생형: 미체결/불명 경로에서 상태 변경 함수가 호출되면 즉시 실패
|
||||
boom = AsyncMock(side_effect=AssertionError("unexpected state mutation"))
|
||||
monkeypatch.setattr(v2, "sync_active_trade_after_manual_sell_v2", boom)
|
||||
monkeypatch.setattr(v2, "reflect_dt_after_manual_sell_v2", boom)
|
||||
return SimpleNamespace(th=th, pf=pf)
|
||||
|
||||
|
||||
def _guard(monkeypatch, qty=3):
|
||||
g = SimpleNamespace(quantity=qty, to_response=lambda: {})
|
||||
monkeypatch.setattr(v2, "evaluate_manual_buy_v2", AsyncMock(return_value=g))
|
||||
import app.services.system_buy_registry as r
|
||||
monkeypatch.setattr(r, "note_system_buy", lambda *a, **k: None)
|
||||
|
||||
|
||||
def _db(holding=None):
|
||||
db = MagicMock()
|
||||
db.execute = AsyncMock(return_value=_Res(holding))
|
||||
return db
|
||||
|
||||
|
||||
def _holding():
|
||||
return SimpleNamespace(quantity=10, stock_name="T", average_price=100.0,
|
||||
strategy_type="swing", current_price=100.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_limit_buy_is_pending(monkeypatch, cap):
|
||||
_guard(monkeypatch)
|
||||
monkeypatch.setattr(v2, "safe_place_order_v2", AsyncMock(return_value={"rt_cd": "0", "output": {"ODNO": "1"}}))
|
||||
await v2._buy_stock_impl_v2(BuyRequest(stock_code=CODE, quantity=3, price=70000), CODE, _db(), _ctx())
|
||||
p = cap.th[0]
|
||||
assert p["status"] == "PENDING" and p["executed_quantity"] == 0 and p["executed_at"] is None
|
||||
cap.pf.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_market_buy_completed(monkeypatch, cap):
|
||||
_guard(monkeypatch)
|
||||
monkeypatch.setattr(v2, "safe_place_order_v2", AsyncMock(return_value={"rt_cd": "0", "output": {"ODNO": "1"}}))
|
||||
await v2._buy_stock_impl_v2(BuyRequest(stock_code=CODE, quantity=3), CODE, _db(), _ctx())
|
||||
assert cap.th[0]["status"] == "COMPLETED" and cap.th[0]["executed_quantity"] == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_buy_pending_and_cooldown(monkeypatch, cap):
|
||||
_guard(monkeypatch)
|
||||
monkeypatch.setattr(v2, "safe_place_order_v2",
|
||||
AsyncMock(return_value={"rt_cd": "-1", "msg_cd": "KIS_TRANSPORT_UNKNOWN"}))
|
||||
with pytest.raises(HTTPException) as e:
|
||||
await v2._buy_stock_impl_v2(BuyRequest(stock_code=CODE, quantity=3), CODE, _db(), _ctx())
|
||||
assert e.value.status_code == 504
|
||||
assert cap.th[0]["status"] == "PENDING" and cap.th[0]["executed_quantity"] == 0
|
||||
assert (1, CODE) in v2._last_done_v2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_sell_no_state_change(monkeypatch, cap):
|
||||
monkeypatch.setattr(v2, "safe_place_order_v2", AsyncMock(return_value={}))
|
||||
with pytest.raises(HTTPException) as e:
|
||||
await v2.sell_stock_v2(SellRequest(stock_code=CODE, quantity=5), _ctx(), _db(_holding()))
|
||||
assert e.value.status_code == 504
|
||||
assert cap.th[0]["status"] == "PENDING"
|
||||
cap.pf.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_limit_sell_pending_no_state_change(monkeypatch, cap):
|
||||
monkeypatch.setattr(v2, "safe_place_order_v2", AsyncMock(return_value={"rt_cd": "0", "output": {"ODNO": "2"}}))
|
||||
r = await v2.sell_stock_v2(SellRequest(stock_code=CODE, quantity=5, price=200.0), _ctx(), _db(_holding()))
|
||||
assert cap.th[0]["status"] == "PENDING" and cap.th[0]["executed_quantity"] == 0
|
||||
assert r["pending"] is True
|
||||
cap.pf.assert_not_called()
|
||||
Reference in New Issue
Block a user