"""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()