Files
trex-core/tests/application/test_update_thresholds_handler.py
T
genichinandClaude Opus 4.8 7d727824dc feat(slot): BAT-030 — 자산 중심 cutover 완성 (dcy-020 BAT-δ, REQ-056·057·062·064·065)
M1 literal inactive 전면화: SlotState 5-state(idle/closed 별칭 제거),
마이그레이션 010(CHECK 교체+행 rewrite), ops_checks 를 transition_log 기반 재작성.
M2 집행 매도 수량 브로커 정본(D3): dispatch 매도 qty=broker hldg_qty,
미러 fallback 없음, 브로커 0 → skip+WARN, 리스트 기반 dispatch(head-block 방지).
M3 컬럼 drop + legacy pool 제거: 마이그레이션 011(trading_date·entry_count DROP),
repo 계약 instance 스코프 개편(집행 큐 포함), preallocation 폐기(데몬 7스레드),
admission 자산 중심 단일 경로(slot_id 정본), capacity 재정의(available=M−active),
daily_symbol_entries 코드 경로 제거.
M4 cutover 도구(D1·D4): trex-core-cutover(전체 rebuild, preflight/브로커 carry-over/
--allow-unmapped/--promote-unique/dry-run) + PG 리허설 테스트 8건.
M5 baseline 마감: data-model/runtime-flows/project-structure/interface-contract
자산 중심 최종 갱신 + run-trex-core-daemon 스킬 정합.

검증: 단위 367 passed + ruff clean; PG-gated 29 passed(010/011 round-trip·드리프트
가드·cutover 리허설); RabbitMQ 21 passed; run-the-app e2e(test DB+실 MQ, M=1):
reconcile 슬롯 생성→slot_id 매수→dedup→capacity_full→fill→already_active→
매도→inactive(자산 바인딩 보존)→영구 슬롯 재활성 전 구간 green.
실 cutover 는 운영자 실행(REL 단계, D4).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 15:16:15 +09:00

136 lines
5.0 KiB
Python

"""update_thresholds intent RPC handler tests (REQ-040 / BAT-011)."""
from __future__ import annotations
from datetime import 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
@pytest.fixture
def repo():
return InMemorySlotRepository()
@pytest.fixture
def service(repo):
return SlotService(repo)
@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):
from uuid import uuid4
pid = f"pf-{uuid4().hex[:8]}"
repo.reconcile_universe("default", {pid})
slot = repo.find_slot_by_portfolio("default", pid)
pending = service.transit_slot(
slot.slot_id, SlotState.INACTIVE, 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."""
repo.reconcile_universe("default", {"pf-inactive"})
inactive = repo.find_slot_by_portfolio("default", "pf-inactive")
resp = handler(_req(slot_id=str(inactive.slot_id), stop_loss_price=50000))
assert resp.payload["status"] == "ignored"
assert resp.payload["reason"] == "not_holding"
assert str(inactive.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"