Files
auto-stock/backend/tests/conftest.py
shuim 9fab4018d4 fix: 프로그램 검증 루프 7회차 — 리스크·주문·청산·인프라 결함 일괄 수정 + 거래 확대 결정 반영
하네스 규칙 검사 전역 위반 117→0, 회차별 검증(code-verifier opus 4도메인)으로 Critical/High 해소.

주문·리스크
- MDD 강제축소 반복 매도(종목별 완료 집합·재시도 상한·날짜 롤오버·잔고 오류 보류·epoch·장외 미주문)
- KIS 거부 FAILED 기록, 결과 불명(전송 후) 재전송 금지·PENDING, 미전송 실패만 재시도(msg_cd 분류)
- 국내 전량·손실 매도 시장가, 부분 익절 직전 현재가, 지정가만 미체결 취소(cancel_order_v2: TR 0013U·조직번호) + 0체결 롤백
- 누적 4%·현금·레버리지(신규분 포함)·사이클 내 매수 누적, 수동매수 공용 가드(buy_guards), 수동매도 DT 차감·락
- 가드 우회 엔드포인트 차단(/recommendations/auto-trade 위임, US /execute 매수 410·매도 가드)
- 매수 슬롯=성공 매수, 평가 상한·회전, 업무거부/계좌 쿨다운, 프로세스 내 in-flight 주문 중복 차단
데이트레이딩
- 진입·청산 shield, 청산 진행 중 표식(소유 토큰), 2단계 청산 체크, 결과 불명 → 보유 감소 판정·비DT 차감 상한
- 전일 포지션 재시도(일시 실패 미산정), 분할매도 영속, ORB 구간 손절, /cycle 락, 사이클 내 현금 차감, 체결 수량 보정
스윙
- 손절 공백(판정 예외 시 하드 바닥), 단일 손절 소스·범위 검증, 매도 직전 KIS 잔고 상한(min(주문가능,보유)−DT)
- 결과 불명 체결 대조·장부 반영, 대체가(나이·진입 이후·ATR 캐시), 분할 단계 기록, 국면 실패 fail-closed
- 듀얼 플레이북·서킷브레이커 게이트, 평균회귀 우선·듀얼 독립, 시간손절 거래일
- 거래 확대(사용자 결정, 백테스트 미검증): RSI 46/35 정본 경로, 모멘텀 v2 ON, SIDEWAYS ADX AND, 트레일링 1차 익절 후, 20일 시간손절 ON
인프라·보안
- 계좌·손익 GET 인증, 세션 is_active·관리자 경로, 서명키 파생, realip, WS 토큰 마스킹
- KIS 토큰 즉시 실패(sleep 제거)·무효 시 캐시 삭제, 주문 5xx+JSON 본문 반환
- db_worker 종료 drain(멱등 재실행·커밋 불명 격리·예산·밴 커밋), stop_grace 40s, Redis 타임아웃·volatile-lru, /health DLQ·캐시
- KRX 휴장일, py3.11 비호환 f-string 수정 + Jenkins 이미지 내 compileall·헬스 실패 시 빌드 실패
하네스: rules_check 에 PEP 701 f-string 검사, 마커(allow-*), deploy 스모크 401 기준
CLAUDE.md: 실제 동작·플래그·백로그(§8.5-27~38) 갱신

backend 1451 passed / hooks 112 passed / tsc ok / py3.9 compile 0 errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 12:01:31 +09:00

226 lines
11 KiB
Python

"""유닛 테스트 계층 공용 안전망 — 실제 KIS 호출·라이브 DB를 구조적으로 차단한다.
## 왜 필요한가
파일별 방어(각 테스트가 자기 목을 다는 방식)는 두 번 실패했다.
1. `test_daytrading_stale_position_guard.py` — 리팩터링으로 `close_stale_positions()`가
`_execute_exit` → `_execute_exit_stale` 로 바뀌자 목이 빗나가 **실제 KIS 매도 주문이
2회 전송**됐다.
2. `test_daytrading_orb_watchlist_and_capital_split.py` — `get_balance`만 목킹하고
`get_buyable_cash()`는 빠뜨려 `_get_access_token → _request_new_token` 으로 내려갔고,
`korea_investment_api._handle_rate_limit()`의 "토큰 발급 1분 제한: 69.8초 대기"
(`asyncio.sleep`)에 걸려 테스트 하나가 140초를 소비했다. 소켓을 막아도 예외가
재시도 로직에 삼켜진 뒤 잠들기 때문에 느려지는 것은 그대로다.
프로젝트 메모리에는 멀티테넌트 1단계 작업 중 라이브 경로 호출로 **모의투자 1주 오발주**
사고가 기록돼 있다. 규약은 "격리 Postgres(`_test` 접미사) + KIS mock"인데 유닛 계층에는
`conftest.py`가 없어 강제 수단이 전혀 없었다.
## 설계 원칙
- **그럴듯한 값을 반환하지 않는다.** 모든 차단 대상은 호출되는 즉시 예외를 던진다.
조용히 성공하는 스텁은 목킹 누락을 감추고 테스트를 거짓 통과시킨다.
- 예외는 `Exception`이 아니라 **`BaseException` 파생**(`KISCallBlocked`)이다.
프로덕션 코드 곳곳의 `except Exception:` 재시도/폴백 블록이 삼켜버리면 차단이 무력화되고
(위 사례 2처럼) 오히려 느려지기만 한다. `BaseException`이면 통과해서 테스트를 실패시킨다.
- **차단은 클래스 메서드에 적용**한다(`KoreaInvestmentAPI.<method>`). 인스턴스가 아니라
클래스를 막아야 `from ... import korea_investment_api`로 싱글톤 참조를 미리 캡처한
모듈(예: `daytrading/entry_service`, `api/endpoints/portfolio`)이나 멀티테넌트에서 새로
만드는 인스턴스까지 전부 덮인다. 개별 테스트의 `patch.object(instance, ...)`는 인스턴스
속성으로 클래스 속성을 가리므로 **테스트 쪽 목이 항상 이긴다**(autouse 픽스처가 먼저
적용되고 테스트 내 patch가 나중에 적용되는 순서).
- **시세·잔고 계열도 차단**한다. 전역 기본 스텁을 주면 기존 테스트의 기대값이 조용히
바뀌므로, 값을 주는 대신 막고 각 테스트가 명시적으로 덮게 한다.
- `tests/integration/`은 제외한다(격리 컨테이너 Postgres + 자체 목 규약, 별도 conftest).
## 사용법
cd backend
DATABASE_URL="postgresql+asyncpg://u:p@127.0.0.1:5432/autostock_test" \
python -m pytest tests/ --ignore=tests/integration
`--allow-network` 를 주면 KIS 차단을 끈다(실 연동 점검 전용, 기본 꺼짐).
"""
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
# ─────────────────────────────────────────────────────────────────────────────
# 차단 예외 — `except Exception:` 에 삼켜지지 않도록 BaseException 파생
# ─────────────────────────────────────────────────────────────────────────────
class KISCallBlocked(BaseException):
"""테스트 중 실제 KIS/주문 경로가 호출됨 — 해당 테스트의 목킹이 누락됐다는 뜻."""
def _blocked(dotted_name: str):
"""호출 즉시 실패하는 async 스텁 — 값을 반환하지 않는다(거짓 통과 방지)."""
async def _boom(*args, **kwargs):
raise KISCallBlocked(
f"[tests/conftest.py] 실호출 차단: {dotted_name}() 가 목킹되지 않은 채 호출됐습니다. "
f"해당 테스트에서 patch.object(...)로 명시적으로 덮으십시오. "
f"(실 연동 점검이라면 tests/integration/ 으로 옮기거나 --allow-network 사용)"
)
_boom.__name__ = dotted_name.rsplit(".", 1)[-1]
_boom.__qualname__ = dotted_name
return _boom
# 차단 대상 — 추측이 아니라 코드에서 정의 위치를 확인한 목록 (2026-09-27 기준).
#
# app/services/korea_investment_api.py
# 174 class KoreaInvestmentAPI
# 410 async def _request_new_token
# 461 async def _get_access_token
# 632 async def get_current_price
# 652 async def get_daily_chart
# 801 async def get_overseas_price
# 822 async def get_minute_chart
# 904 async def get_minute_chart_full_day
# 1001 async def get_overseas_daily_chart
# 1044 async def place_overseas_order
# 1087 async def get_balance
# 1164 async def get_buyable_cash
# 1202 async def get_overseas_balance
# 1234 async def place_order
# app/services/trade_executor.py
# 260 async def safe_place_order
# 334 async def safe_place_order_v2
_KIS_CLASS_METHODS = (
# ── 주문 계열 (실발주 위험) ──
"place_order",
"place_overseas_order",
"cancel_order", # [2026-10-02 r4] 미체결 매도 자동 취소 경로가 생겨 실주문 계열로 차단
"cancel_order_v2", # [2026-10-02 r5] 레거시 cancel_order 가 위임하는 실취소 경로
# ── 토큰 계열 (rate-limit sleep 70초의 근원) ──
"_request_new_token",
"_get_access_token",
# ── 시세·잔고 계열 ──
"get_current_price",
"get_daily_chart",
"get_overseas_price",
"get_overseas_daily_chart",
"get_minute_chart",
"get_minute_chart_full_day",
"get_minute_chart_full_day_v2", # 진입 판정 경로(전일 워밍업 포함) — 2026-09-29
"get_balance",
"get_buyable_cash",
"get_overseas_balance",
# ── 체결 조회 계열 (2026-10-01: DT 체결가 확인이 백그라운드로 호출) ──
"get_todays_orders",
"get_order_execution",
)
_TRADE_EXECUTOR_FUNCS = (
"safe_place_order",
"safe_place_order_v2",
)
# ─────────────────────────────────────────────────────────────────────────────
# pytest 훅
# ─────────────────────────────────────────────────────────────────────────────
def pytest_addoption(parser):
parser.addoption(
"--allow-network",
action="store_true",
default=False,
help="KIS 실호출 차단을 해제한다 (실 연동 점검 전용 — 라이브 계좌 주문 위험).",
)
def pytest_configure(config):
"""라이브 DB 가드 — DB 이름이 `_test`로 끝나지 않으면 세션 자체를 중단.
`tests/integration/conftest.py` 도 동일한 가드를 import 시점에 수행한다. 여기서는
유닛 계층까지 포함해 세션 전체에 적용하되, 판정 기준(`settings.DATABASE_URL`의 DB 이름)이
같으므로 integration 단독 실행의 기존 동작은 바뀌지 않는다. env만 보던 방식은
env 미설정 시 `settings.DATABASE_URL` 기본값(라이브 가능성)으로 조용히 새는 결함이 있어
`settings`를 기준으로 본다.
"""
from app.core.config import settings
db_url = settings.DATABASE_URL or os.environ.get("DATABASE_URL") or ""
db_name = db_url.rsplit("/", 1)[-1].split("?", 1)[0]
if not db_name.endswith("_test"):
pytest.exit(
"settings.DATABASE_URL의 DB 이름이 '_test'로 끝나지 않습니다"
f"(현재: {db_name!r}). 테스트는 반드시 격리 DB(예: autostock_test)를 대상으로 "
"실행해야 합니다. 예:\n"
' DATABASE_URL="postgresql+asyncpg://u:p@127.0.0.1:5432/autostock_test" '
"python -m pytest tests/ --ignore=tests/integration",
returncode=1,
)
def _is_integration(request) -> bool:
"""`tests/integration/` 하위이거나 `integration` 마커가 붙은 테스트인가."""
try:
path = str(request.node.fspath)
except Exception: # pragma: no cover - fspath 미지원 노드 방어
path = ""
if f"{os.sep}integration{os.sep}" in path:
return True
return request.node.get_closest_marker("integration") is not None
@pytest.fixture(autouse=True)
def _reset_order_inflight_locks():
"""[2026-10-02 r5] trade_executor 프로세스 내 주문 in-flight 표는 모듈 전역이라 테스트 간에
샌다(락만 잡고 해제하지 않는 단위 테스트가 다음 테스트의 같은 종목 주문을 막는다)."""
from app.services import trade_executor as _te
_te._inflight_order_locks.clear()
yield
_te._inflight_order_locks.clear()
@pytest.fixture(autouse=True)
def _block_live_kis(request, monkeypatch):
"""모든 유닛 테스트에 자동 적용 — KIS 주문/토큰/시세/잔고 경로를 호출 즉시 실패로 치환.
적용 순서상 이 픽스처가 먼저 클래스 속성을 덮고, 테스트 본문의
`patch.object(instance, ...)` / `patch("...module.attr", ...)` 가 나중에 적용되므로
개별 테스트의 명시적 목이 항상 우선한다.
"""
if request.config.getoption("--allow-network"):
return
if _is_integration(request):
return
from app.services import korea_investment_api as kis_mod
for name in _KIS_CLASS_METHODS:
if not hasattr(kis_mod.KoreaInvestmentAPI, name):
raise AssertionError(
f"tests/conftest.py 차단 목록이 코드와 어긋납니다: "
f"KoreaInvestmentAPI.{name} 가 존재하지 않습니다(이름 변경/삭제?)."
)
monkeypatch.setattr(
kis_mod.KoreaInvestmentAPI,
name,
_blocked(f"korea_investment_api.{name}"),
raising=True,
)
from app.services import trade_executor as te_mod
for name in _TRADE_EXECUTOR_FUNCS:
if not hasattr(te_mod, name):
raise AssertionError(
f"tests/conftest.py 차단 목록이 코드와 어긋납니다: "
f"trade_executor.{name} 가 존재하지 않습니다(이름 변경/삭제?)."
)
monkeypatch.setattr(
te_mod, name, _blocked(f"trade_executor.{name}"), raising=True
)
# [2026-10-01] DT 체결가 확인(daytrading/fill_reconciler)은 주문 직후 백그라운드 태스크를
# 띄운다. 유닛 테스트에서는 기본 OFF — 테스트 종료 뒤 남은 태스크가 차단된 KIS 를 치거나
# "Task was destroyed but it is pending" 노이즈를 내지 않게 한다. 검증하는 테스트만 켠다.
from app.core.config import settings as _settings
monkeypatch.setattr(_settings, "DAY_TRADE_FILL_CHECK_ENABLED", False, raising=False)