Files
trex-core/tests/runtime/test_instance_config.py
genichinandClaude Sonnet 4.6 e4e5c70422 feat(bat-053): 그날-시작 KIS 인증정보 fetch + fail-safe 로드 (REQ-112~115)
REQ-112: BrokerCredentialPayload/TradingContext 데이터클래스 + PortfolioHubReadPort.fetch_broker_credential() 포트 메서드 + hub_read 어댑터(_fetch_user_info 헬퍼 추출) + stub_read 결정론 stub
REQ-113: DaemonInstanceConfig/DaemonConfig.credential_fetch_enabled opt-in(기본 False) + TOML 파싱 + break-glass(TREX_KIS_BROKER_BREAK_GLASS) 감지
REQ-114: SnapshotScheduler._maybe_fetch_credential() — fail-closed 3조건(unavailable/broker-null/trading_disabled) + CRITICAL 알람 DAY_START_LOAD_FAILED + IntentService entry_allowed_fn 게이트(BuyIntent 차단, SellIntent 통과)
REQ-115: 그날 고정 캐시(_cached_credential/_credential_date) — 동일 날짜 재fetch 방지 + app_secret 메모리 한정(Redis 미기록)

스텁 기반 구현: 실 portfolio-hub/네트워크 없이 AC 전부 단위 테스트.
회귀: credential_fetch_enabled=False(기본) 경로 byte-for-byte 보존.
745 passed, 47 skipped (0 failed).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-28 11:00:18 +09:00

150 lines
6.3 KiB
Python

"""Per-instance TOML config loader tests (REQ-048 / BAT-013)."""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
import pytest
from trex_core.runtime.config import DaemonConfig, DaemonInstanceConfig
_REPO = Path(__file__).resolve().parents[2]
def _write_toml(tmp_path, body: str) -> str:
p = tmp_path / "inst.toml"
p.write_text(body)
return str(p)
def test_from_toml_parses(tmp_path):
"""AC-1: from_toml reads instance_key + portfolio_hub_token."""
path = _write_toml(tmp_path, 'instance_key = "inst-1"\nportfolio_hub_token = "tok"\n')
cfg = DaemonInstanceConfig.from_toml(path)
assert cfg.instance_key == "inst-1"
assert cfg.portfolio_hub_token == "tok"
def test_from_toml_missing_instance_key_raises(tmp_path):
"""AC-4: missing required instance_key → error (no silent default)."""
path = _write_toml(tmp_path, 'portfolio_hub_token = "tok"\n')
with pytest.raises(RuntimeError):
DaemonInstanceConfig.from_toml(path)
def test_from_config_injects_token(tmp_path, monkeypatch):
"""AC-3 / S-5: TOML token is injected into PortfolioHubConfig when base_url is set,
even with TREX_PORTFOLIO_HUB_TOKEN absent from the environment."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
monkeypatch.setenv("TREX_PORTFOLIO_HUB_BASE_URL", "http://hub:18000")
monkeypatch.delenv("TREX_PORTFOLIO_HUB_TOKEN", raising=False)
path = _write_toml(tmp_path, 'instance_key = "inst-9"\nportfolio_hub_token = "toml-tok"\n')
cfg = DaemonConfig.from_config(path)
assert cfg.instance_key == "inst-9"
assert cfg.portfolio_hub is not None
assert cfg.portfolio_hub.token == "toml-tok"
def test_default_instance_key_when_from_env(monkeypatch):
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
assert DaemonConfig.from_env().instance_key == "default"
def test_trading_timezone_defaults_to_kst(tmp_path, monkeypatch):
"""dcy-014 / REQ-048: trading TZ defaults to KST (preallocation trigger
removed at BAT-030 with the pool model)."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
inst = DaemonInstanceConfig.from_toml(_write_toml(tmp_path, 'instance_key = "i1"\n'))
assert inst.trading_timezone == "Asia/Seoul"
assert DaemonConfig.from_env().trading_timezone == "Asia/Seoul"
def test_trading_timezone_from_toml_propagates(tmp_path, monkeypatch):
"""dcy-014 / REQ-048: TOML trading_timezone + trigger flow into DaemonConfig."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
path = _write_toml(
tmp_path,
'instance_key = "i2"\ntrading_timezone = "UTC"\n',
)
cfg = DaemonConfig.from_config(path)
assert cfg.trading_timezone == "UTC"
def test_config_required_cli_exits_nonzero():
"""AC-2: daemon entry without --config exits non-zero (argparse required)."""
proc = subprocess.run(
[sys.executable, "-m", "trex_core.runtime.daemon"],
capture_output=True, text=True, timeout=30, cwd=str(_REPO),
)
assert proc.returncode != 0
assert "config" in (proc.stderr + proc.stdout).lower()
def test_gitignore_excludes_instance_toml():
"""AC-5 (CHG-20260609-01): .gitignore ignores config/* but keeps example
templates (*.example.toml covers instance.example.toml) and .env.example."""
gi = (_REPO / ".gitignore").read_text()
assert "/config/*" in gi
assert "!/config/*.example.toml" in gi
assert "!/config/.env.example" in gi
# --- safety_sell_enabled (REQ-048 CHG-20260611-01, BAT-036) -----------------
def test_safety_sell_enabled_default_true(tmp_path, monkeypatch):
"""AC-10: absent from TOML → safety_sell_enabled=True (default on)."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
inst = DaemonInstanceConfig.from_toml(_write_toml(tmp_path, 'instance_key = "i3"\n'))
assert inst.safety_sell_enabled is True
cfg = DaemonConfig.from_config(_write_toml(tmp_path, 'instance_key = "i3"\n'))
assert cfg.safety_sell_enabled is True
def test_safety_sell_enabled_false_from_toml(tmp_path, monkeypatch):
"""AC-10: safety_sell_enabled = false in TOML → DaemonConfig.safety_sell_enabled=False."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
path = _write_toml(tmp_path, 'instance_key = "i4"\nsafety_sell_enabled = false\n')
cfg = DaemonConfig.from_config(path)
assert cfg.safety_sell_enabled is False
def test_safety_sell_enabled_true_explicit_from_toml(tmp_path, monkeypatch):
"""AC-10: safety_sell_enabled = true in TOML → DaemonConfig.safety_sell_enabled=True."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
path = _write_toml(tmp_path, 'instance_key = "i5"\nsafety_sell_enabled = true\n')
cfg = DaemonConfig.from_config(path)
assert cfg.safety_sell_enabled is True
# --- credential_fetch_enabled (REQ-113 / BAT-053) ---------------------------
def test_credential_fetch_enabled_default_false_from_toml(tmp_path, monkeypatch):
"""REQ-113 AC-7: TOML에 credential_fetch_enabled 없으면 False (opt-in 기본값)."""
inst = DaemonInstanceConfig.from_toml(_write_toml(tmp_path, 'instance_key = "i6"\n'))
assert inst.credential_fetch_enabled is False
def test_credential_fetch_enabled_false_propagates(tmp_path, monkeypatch):
"""REQ-113 AC-1: credential_fetch_enabled=false(부재 포함) → DaemonConfig False."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
cfg = DaemonConfig.from_config(_write_toml(tmp_path, 'instance_key = "i7"\n'))
assert cfg.credential_fetch_enabled is False
def test_credential_fetch_enabled_true_from_toml(tmp_path, monkeypatch):
"""REQ-113 AC-7: TOML에 credential_fetch_enabled = true → True 전파."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
path = _write_toml(tmp_path, 'instance_key = "i8"\ncredential_fetch_enabled = true\n')
inst = DaemonInstanceConfig.from_toml(path)
assert inst.credential_fetch_enabled is True
cfg = DaemonConfig.from_config(path)
assert cfg.credential_fetch_enabled is True
def test_from_env_credential_fetch_enabled_always_false(monkeypatch):
"""REQ-113 AC-1: from_env()는 항상 credential_fetch_enabled=False(env-only 경로 보존)."""
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
cfg = DaemonConfig.from_env()
assert cfg.credential_fetch_enabled is False