"""감사 P2 수정 검증: 주문 멱등성 / shield / 다중행 / v2·수동매도 / 스윙 쿨다운.""" import asyncio import inspect from unittest.mock import AsyncMock, patch import pytest from app.services import trade_executor as te from app.services.korea_investment_api import KoreaInvestmentAPI def test_order_endpoints_not_retried_internally(): """주문은 내부 재시도 금지 — 상위 재시도와 중첩되면 동일 주문이 최대 12회 전송된다.""" src = inspect.getsource(KoreaInvestmentAPI._make_request_with_retry) assert "_max_retries = 0 if endpoint in self._NON_IDEMPOTENT_ENDPOINTS" in src # 재시도 판단은 전부 _max_retries 기준이어야 한다 (원본 self.max_retries 사용 금지) body = src.split("for attempt in range(_max_retries + 1):", 1)[1] assert "self.max_retries" not in body, "재시도 루프 안에 원본 max_retries 잔존" assert body.count("attempt < _max_retries") == 2 # 5xx/429 경로 + 타임아웃 경로 eps = KoreaInvestmentAPI._NON_IDEMPOTENT_ENDPOINTS assert "/uapi/domestic-stock/v1/trading/order-cash" in eps assert "/uapi/overseas-stock/v1/trading/order" in eps @pytest.mark.asyncio async def test_retry_stops_when_order_already_accepted(): """타임아웃 후 재시도 전에 접수된 주문을 발견하면 재주문하지 않는다.""" calls = {"n": 0} async def _boom(*a, **k): calls["n"] += 1 raise TimeoutError("no response") dup = {"rt_cd": "0", "odno": "0000012345", "output": {"ODNO": "0000012345"}} with patch.object(te.korea_investment_api, "place_order", _boom), \ patch.object(te, "_find_recent_order", AsyncMock(return_value=dup)): out = await te._place_order_with_retry( stock_code="005930", order_type="SELL", quantity=3, price=None, is_domestic=True, ) assert out["odno"] == "0000012345" assert calls["n"] == 1, "중복 확인 후에도 재주문이 나감" @pytest.mark.asyncio async def test_find_recent_order_matches_side_and_qty(): rows = [ {"pdno": "005930", "sll_buy_dvsn_cd": "01", "ord_qty": "3", "ord_tmd": "103000", "odno": "A1"}, {"pdno": "005930", "sll_buy_dvsn_cd": "02", "ord_qty": "3", "ord_tmd": "103000", "odno": "B1"}, ] from datetime import datetime as _dt class _FakeDT(_dt): @classmethod def now(cls, tz=None): return _dt(2026, 9, 23, 10, 30, 30) with patch.object(te.korea_investment_api, "get_todays_orders", AsyncMock(return_value=rows)), \ patch.object(te, "datetime", _FakeDT): sell = await te._find_recent_order("005930", "SELL", 3) buy = await te._find_recent_order("005930", "BUY", 3) none = await te._find_recent_order("005930", "SELL", 5) assert sell["odno"] == "A1" # 01 = 매도 assert buy["odno"] == "B1" # 02 = 매수 assert none is None # 수량 불일치 @pytest.mark.asyncio async def test_dt_exit_state_update_is_shielded(): """DT 청산의 '체결 이후 상태 반영' 은 취소로부터 보호(asyncio.shield)되어야 한다. 과거 버그(P2 감사): 스케줄러 단계 타임아웃(_guard)이 매도 주문 직후를 취소하면 "브로커는 팔았는데 인메모리 포지션은 그대로" 가 되어 다음 사이클이 같은 물량을 다시 팔았다(미보유 매도/중복 매도). [2026-09-27] `_execute_exit` 가 `_execute_exit_impl` 로 위임하고 shield 는 impl 안 2곳(`_finalize_exit` / `_finalize_exit_stale`)으로 이동 — 동작은 보존됐고 `_execute_exit` 본문만 보던 문자열 가드의 **검사 범위**가 어긋났다. 이제 문자열이 아니라 **동작**을 본다: 주문 체결 직후 태스크를 취소해도 finalize 가 끝까지 완주하는지 확인한다(shield 제거 시 반드시 실패). """ from app.services.daytrading import exit_service as es finished: list = [] async def _fake_finalize(*args, **kwargs): await asyncio.sleep(0.05) # 취소가 개입할 수 있는 지점 finished.append(True) # shield 가 있으면 여기까지 도달 return {"stock_code": "005930"} with patch.object(es, "_finalize_exit", _fake_finalize), \ patch("app.services.trade_executor.safe_place_order", AsyncMock(return_value={"rt_cd": "0", "output": {"ODNO": "1"}})): task = asyncio.create_task( es._execute_exit("005930", {"quantity": 10}, 1000.0, "테스트 청산") ) await asyncio.sleep(0.01) # 주문 완료 후 finalize 진입까지 진행 task.cancel() with pytest.raises(asyncio.CancelledError): await task await asyncio.sleep(0.1) # shield 된 내부 코루틴 완주 대기 assert finished, "체결 후 상태 반영이 취소됐다 — shield 누락 (중복 매도 위험)" # 상태 반영 구현(인메모리 제거 + DB 기록)이 유지되는지 — 위임 체인을 따라 확인 fin = inspect.getsource(es._finalize_exit) if "_finalize_exit_impl" in fin: fin += inspect.getsource(es._finalize_exit_impl) assert "remove_position" in fin and "enqueue_trade_history" in fin # 전일(stale) 청산 경로도 동일하게 보호되어야 한다 impl = inspect.getsource(es._execute_exit_impl) assert "asyncio.shield(_finalize_exit_stale(" in impl # shield 는 반드시 주문 전송 '이후' 여야 한다(주문 실패 시 상태 반영 금지) assert impl.index("safe_place_order(") < impl.index("asyncio.shield(") def test_swing_active_trade_lookup_handles_multiple_rows(): from app.services.swing import position_manager as pm src = inspect.getsource(pm.get_swing_active_trade) code = "\n".join(l for l in src.splitlines() if "#" not in l and '"""' not in l) assert "scalar_one_or_none" not in code, "행 2개면 예외 → 손절 통째 스킵" assert "order_by(ActiveTrade.id.desc())" in src and "scalars().first()" in src def test_swing_exit_has_repeat_guard(): from app.services.swing import exit_service as se assert se.EXIT_COOLDOWN_SEC >= 60 src = inspect.getsource(se.check_and_execute_exit_v2) assert "_recent_exits" in src and "쿨다운" in src def test_v2_sell_maps_strategy_name_and_updates_quantity(): from app.api.endpoints import portfolio_v2 as v2 src = inspect.getsource(v2) assert '"daytrading": "day_trade"' in src and '"us_swing": "us_mean_reversion"' in src assert '"quantity": original_holding_qty - quantity' in src def test_manual_sell_uses_lock_and_updates_dt_state(): from app.api.endpoints import portfolio as pf src = inspect.getsource(pf.sell_stock) assert "safe_place_order(" in src, "락 없는 직접 주문" assert "day_trading_state" in src and "remove_position" in src