Files
trex-core/tests/application/test_update_thresholds_handler.py
T
genichinandClaude Opus 4.8 a30efa8f3b feat(safety-sell): dcy-007 core 자율 안전 매도 — BAT-010 기반 + BAT-011 트리거
dcy-007(core 자율 안전 매도) 전체 delivery. BAT-010 기반 인프라가 미커밋
상태였고 BAT-011 트리거 레이어와 공유 파일에서 섞여 있어 한 커밋으로 묶음.

BAT-010 (REQ-034/035/036/041, release-candidate):
- WatchdogStore(application/watchdog.py) + snapshot RPC 워치독 갱신
- Slot stop_loss_price/take_profit_price 필드 + 004_add_price_thresholds.sql
- SlotService.sell() 자율 매도 내부 경로 + idempotency
- SafetySellConfig env 5종 파싱

BAT-011 (REQ-037/038/039/040/042, release-candidate):
- SafetySellService(application/safety_sell.py): forced_close 만기 / stop-loss·
  take-profit KIS polling / 장 마감 강제 청산 + trex-safety-sell 7번째 스레드
- BrokerPort.get_current_price + KIS inquire-price(TTTC8397R/VTTC8397R, stck_prpr)
  + paper stub
- SlotService.update_thresholds() + intent RPC update_thresholds 액션
  (부분 갱신/null 해제, 워치독 last_seen_at 리셋)
- baseline 3문서 정합(interface-contract/runtime-flows/project-structure)

거버넌스: REQ-034~042 Implemented 동기화, BAT-010/011 release-candidate,
dcy-007 discovery 포함.

검증: 신규 38 테스트 green, 단위 236 passed/23 skipped,
인프라 게이트(PG+RabbitMQ) 259 passed(마이그레이션 001~004 round-trip 포함),
ruff clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-07 08:32:30 +09:00

136 lines
4.9 KiB
Python

"""update_thresholds intent RPC handler tests (REQ-040 / BAT-011)."""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
import pytest
from trex_core.application.intents import IntentService
from trex_core.application.messaging import RpcRequest
from trex_core.application.messaging_handlers import make_intent_rpc_handler
from trex_core.application.watchdog import WatchdogStore
from trex_core.domain.slot import SlotService, SlotState
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
_DAY = date(2026, 6, 7)
@pytest.fixture
def repo():
return InMemorySlotRepository()
@pytest.fixture
def service(repo):
svc = SlotService(repo)
svc.preallocate_daily_slots(_DAY, 3)
return svc
@pytest.fixture
def watchdog():
return WatchdogStore()
@pytest.fixture
def handler(repo, service, watchdog):
intent_service = IntentService(service, repo, repo._intent_store if hasattr(repo, "_intent_store") else _StubIntentStore())
return make_intent_rpc_handler(intent_service, slot_service=service, watchdog_store=watchdog)
class _StubIntentStore:
def try_insert(self, *a, **k):
return True
def _holding(service, repo, *, symbol="005930", stop_loss_price=None,
take_profit_price=None, forced_close_at=None):
idle = repo.find_idle_slot(_DAY)
pending = service.transit_slot(
idle.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
reason="buy", actor="test", symbol=symbol,
stop_loss_price=stop_loss_price, take_profit_price=take_profit_price,
forced_close_at=forced_close_at,
)
return service.transit_slot(
pending.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="filled", actor="test", avg_price=50000.0, qty=1.0,
)
def _req(**body):
return RpcRequest(payload={"action": "update_thresholds", **body}, correlation_id="c1")
def test_updates_stop_loss(handler, service, repo):
"""AC-1: stop_loss_price is updated in the slot."""
slot = _holding(service, repo)
resp = handler(_req(slot_id=str(slot.slot_id), stop_loss_price=50000))
assert resp.payload["status"] == "updated"
assert repo.fetch_slot(slot.slot_id).stop_loss_price == Decimal("50000")
def test_updates_take_profit_and_forced_close(handler, service, repo):
"""AC-2: take_profit_price and forced_close_at updated together."""
slot = _holding(service, repo)
resp = handler(_req(
slot_id=str(slot.slot_id),
take_profit_price=80000,
forced_close_at="2026-06-07T15:10:00+09:00",
))
assert resp.payload["status"] == "updated"
updated = repo.fetch_slot(slot.slot_id)
assert updated.take_profit_price == Decimal("80000")
assert updated.forced_close_at == datetime.fromisoformat("2026-06-07T15:10:00+09:00")
def test_resets_watchdog_last_seen(handler, service, repo, watchdog):
"""AC-3: update_thresholds resets the watchdog last_seen_at."""
slot = _holding(service, repo)
assert str(slot.slot_id) not in watchdog._store
handler(_req(slot_id=str(slot.slot_id), stop_loss_price=50000))
assert str(slot.slot_id) in watchdog._store
def test_partial_update_keeps_other_fields(handler, service, repo):
"""AC-4: omitted fields keep their current value."""
slot = _holding(service, repo, take_profit_price=Decimal("90000"))
handler(_req(slot_id=str(slot.slot_id), stop_loss_price=50000))
updated = repo.fetch_slot(slot.slot_id)
assert updated.stop_loss_price == Decimal("50000")
assert updated.take_profit_price == Decimal("90000") # untouched
def test_explicit_null_clears(handler, service, repo):
"""AC-5: explicit null clears the threshold."""
slot = _holding(service, repo, stop_loss_price=Decimal("50000"))
handler(_req(slot_id=str(slot.slot_id), stop_loss_price=None))
assert repo.fetch_slot(slot.slot_id).stop_loss_price is None
def test_non_holding_ignored(handler, service, repo, watchdog):
"""AC-6: non-holding slot → ignored + not_holding reason, no watchdog reset."""
service.preallocate_daily_slots(_DAY, 3)
idle = repo.find_idle_slot(_DAY)
resp = handler(_req(slot_id=str(idle.slot_id), stop_loss_price=50000))
assert resp.payload["status"] == "ignored"
assert resp.payload["reason"] == "not_holding"
assert str(idle.slot_id) not in watchdog._store
def test_reply_updated_status(handler, service, repo):
"""AC-7: success returns {status: updated, slot_id}."""
slot = _holding(service, repo)
resp = handler(_req(slot_id=str(slot.slot_id), forced_close_at="2026-06-07T15:10:00+09:00"))
assert resp.payload == {"status": "updated", "slot_id": str(slot.slot_id)}
def test_unknown_slot_ignored(handler):
"""Unknown slot → ignored + slot_not_found reason."""
from uuid import uuid4
sid = uuid4()
resp = handler(_req(slot_id=str(sid), stop_loss_price=50000))
assert resp.payload["status"] == "ignored"
assert resp.payload["reason"] == "slot_not_found"