Files
auto-stock/backend/tests/test_trade_executor.py
shuim de7921d270 fix: CRITICAL/HIGH 버그 30건 수정 + 전체 코드 주석 추가 + 중복 정리
## CRITICAL 수정 (20건)
- day_trading: global 선언 누락, loss_tracker 연동, ban 체크 추가
- trade_executor: BUY 체결가 order_price로 수정, remaining_pct 누적 계산
- risk_validator: get_current_price dict 파싱, MAX_POSITION_SIZE 동기화, DB 세션 누수
- risk_management/recommendations: date.today() → KST 변환
- mdd_manager: Lock 밖 executed_key 참조 수정
- correlation_filter: output → output2 키 수정
- portfolio: 해외 종목 USD/KRW 환율 적용 분리
- Sharpe Ratio 거래빈도 기반 연간화
- telegram_notifier: send_message() 공개 래퍼 추가
- position_manager: 앱 재시작 시 DB 포지션 복원
- swing exit_service: remaining_pct 조건 범위 수정
- run_backtest: original_qty 기반 remaining_pct 계산
- us_market_schedule: 2027년 미국 공휴일 추가
- Login.tsx: res.ok 검증 추가
- mean_reversion_strategy: RSI 로그 하드코딩 수정

## HIGH 수정 (10건)
- db_worker: DLQ 파일 백업 메커니즘 추가
- korea_investment_api: 만료 토큰 임의 연장 제거
- market_data: chart_cache 최대 100개 + TTL 만료
- main.py: rate_limit_store 1시간 미접근 IP 정리
- recommendations: fire-and-forget try/except 추가
- swing/scheduler: DB 세션 3개 분리
- Dashboard: wsMessages 전체 순회
- Layout: /health 엔드포인트 + 30초 폴링
- ml_ensemble: POST /train require_api_key 추가
- day_trading: record_trade_result_safe() 전환

## 코드 정리
- 프론트엔드: isUsStock, formatTime 공통 유틸 추출
- 백엔드: dead code 제거, 중복 import 통합
- MCP: JSON 파싱 헬퍼 추출 (~60줄 감소)
- 전체 ~100개 파일 한국어 주석 추가
- 테스트 13건 코드 기준 수정 (468 passed)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 16:05:41 +09:00

608 lines
25 KiB
Python

"""
자동매매 실행 엔진 (trade_executor.py) 유닛 테스트
테스트 시나리오:
1. 세마포어 관리 — _cleanup_semaphores(), _get_order_semaphore()
2. Redis 분산락 — _acquire_order_lock(), _release_order_lock()
3. 주문 재시도 — _place_order_with_retry() (성공·실패·최대재시도 소진)
4. 신호 분류 — BUY/SELL/STRONG_BUY/BLOCK 키워드 매칭
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
import asyncio
import pytest
from unittest.mock import AsyncMock, Mock, patch, MagicMock
from app.services.signal_types import (
BuySignal,
SellSignal,
StrongBuySignal,
BlockSignal,
BUY_KEYWORDS,
SELL_KEYWORDS,
STRONG_BUY_KEYWORDS,
BLOCK_KEYWORDS,
)
# ═══════════════════════════════════════════════════════════════════════════════
# 1. 세마포어 관리 테스트
# ═══════════════════════════════════════════════════════════════════════════════
class TestCleanupSemaphores:
"""_cleanup_semaphores() 테스트"""
def setup_method(self):
"""각 테스트 전 세마포어 딕셔너리 초기화"""
from app.services import trade_executor
trade_executor._order_semaphores.clear()
def test_no_cleanup_under_limit(self):
"""임계값 이하일 때 정리하지 않음"""
from app.services.trade_executor import _cleanup_semaphores, _order_semaphores, _SEMAPHORE_MAX_SIZE
# _SEMAPHORE_MAX_SIZE(200) 이하 → 아무 일도 안 함
for i in range(50):
_order_semaphores[f"CODE_{i:04d}"] = asyncio.Semaphore(1)
_cleanup_semaphores()
assert len(_order_semaphores) == 50
def test_cleanup_removes_unlocked_semaphores(self):
"""임계값 초과 시 잠기지 않은(미사용) 세마포어 제거"""
from app.services.trade_executor import _cleanup_semaphores, _order_semaphores, _SEMAPHORE_MAX_SIZE
# 201개 세마포어 생성 (모두 unlocked — _value == 1)
for i in range(_SEMAPHORE_MAX_SIZE + 1):
_order_semaphores[f"CODE_{i:04d}"] = asyncio.Semaphore(1)
_cleanup_semaphores()
# 전부 unlocked 이므로 전부 제거됨
assert len(_order_semaphores) == 0
def test_cleanup_preserves_locked_semaphores(self):
"""사용 중(locked)인 세마포어는 유지"""
from app.services.trade_executor import _cleanup_semaphores, _order_semaphores, _SEMAPHORE_MAX_SIZE
for i in range(_SEMAPHORE_MAX_SIZE + 1):
sem = asyncio.Semaphore(1)
_order_semaphores[f"CODE_{i:04d}"] = sem
# 3개의 세마포어를 locked 상태로 만듦 (_value == 0)
locked_codes = ["CODE_0010", "CODE_0050", "CODE_0100"]
for code in locked_codes:
_order_semaphores[code]._value = 0 # acquire 된 상태 시뮬레이션
_cleanup_semaphores()
# locked 3개만 남아야 함
assert len(_order_semaphores) == 3
for code in locked_codes:
assert code in _order_semaphores
def test_cleanup_at_exact_limit(self):
"""딱 임계값일 때 정리하지 않음"""
from app.services.trade_executor import _cleanup_semaphores, _order_semaphores, _SEMAPHORE_MAX_SIZE
for i in range(_SEMAPHORE_MAX_SIZE):
_order_semaphores[f"CODE_{i:04d}"] = asyncio.Semaphore(1)
_cleanup_semaphores()
assert len(_order_semaphores) == _SEMAPHORE_MAX_SIZE
class TestGetOrderSemaphore:
"""_get_order_semaphore() 테스트"""
def setup_method(self):
from app.services import trade_executor
trade_executor._order_semaphores.clear()
def test_creates_new_semaphore(self):
"""새로운 종목 코드에 대해 세마포어 생성"""
from app.services.trade_executor import _get_order_semaphore, _order_semaphores
sem = _get_order_semaphore("005930")
assert isinstance(sem, asyncio.Semaphore)
assert "005930" in _order_semaphores
def test_reuses_existing_semaphore(self):
"""동일 종목 코드에 대해 기존 세마포어 반환"""
from app.services.trade_executor import _get_order_semaphore
sem1 = _get_order_semaphore("005930")
sem2 = _get_order_semaphore("005930")
assert sem1 is sem2
def test_different_codes_get_different_semaphores(self):
"""서로 다른 종목 코드는 서로 다른 세마포어"""
from app.services.trade_executor import _get_order_semaphore
sem_samsung = _get_order_semaphore("005930")
sem_sk = _get_order_semaphore("000660")
assert sem_samsung is not sem_sk
def test_triggers_cleanup_when_over_limit(self):
"""한도 초과 시 _cleanup_semaphores 호출 확인"""
from app.services.trade_executor import _get_order_semaphore, _order_semaphores, _SEMAPHORE_MAX_SIZE
# 201개까지 채운 뒤 새 코드 요청 → cleanup 트리거
for i in range(_SEMAPHORE_MAX_SIZE + 1):
_order_semaphores[f"CODE_{i:04d}"] = asyncio.Semaphore(1)
with patch("app.services.trade_executor._cleanup_semaphores") as mock_cleanup:
_get_order_semaphore("NEW_CODE")
# 이미 _order_semaphores에 없으므로 cleanup 호출
mock_cleanup.assert_called_once()
# ═══════════════════════════════════════════════════════════════════════════════
# 2. Redis 분산락 테스트
# ═══════════════════════════════════════════════════════════════════════════════
class TestAcquireOrderLock:
"""_acquire_order_lock() 테스트"""
@pytest.mark.asyncio
async def test_lock_success(self):
"""Redis SET NX 성공 시 True 반환"""
mock_client = AsyncMock()
mock_client.set = AsyncMock(return_value=True)
with patch("app.core.redis.get_redis", return_value=mock_client):
from app.services.trade_executor import _acquire_order_lock
result = await _acquire_order_lock("005930", "buy")
assert result is True
mock_client.set.assert_called_once_with(
"order_lock:005930:buy", "1", nx=True, ex=60
)
@pytest.mark.asyncio
async def test_lock_failure_key_exists(self):
"""이미 락이 존재하면 False 반환"""
mock_client = AsyncMock()
mock_client.set = AsyncMock(return_value=None) # NX 실패 → None
with patch("app.core.redis.get_redis", return_value=mock_client):
from app.services.trade_executor import _acquire_order_lock
result = await _acquire_order_lock("005930", "buy")
assert result is False
@pytest.mark.asyncio
async def test_lock_redis_unavailable(self):
"""Redis 미연결 시 True 반환 (락 없이 진행)"""
with patch("app.core.redis.get_redis", return_value=None):
from app.services.trade_executor import _acquire_order_lock
result = await _acquire_order_lock("005930", "buy")
assert result is True
@pytest.mark.asyncio
async def test_lock_redis_exception(self):
"""Redis 연결 오류 시 True 반환 (세마포어가 대신 보호)"""
with patch(
"app.core.redis.get_redis",
side_effect=ConnectionError("Redis connection refused"),
):
from app.services.trade_executor import _acquire_order_lock
result = await _acquire_order_lock("005930", "sell")
assert result is True
@pytest.mark.asyncio
async def test_lock_key_format(self):
"""락 키 형식이 order_lock:{stock_code}:{order_type} 인지 확인"""
mock_client = AsyncMock()
mock_client.set = AsyncMock(return_value=True)
with patch("app.core.redis.get_redis", return_value=mock_client):
from app.services.trade_executor import _acquire_order_lock
await _acquire_order_lock("AAPL", "sell")
call_args = mock_client.set.call_args
assert call_args[0][0] == "order_lock:AAPL:sell"
class TestReleaseOrderLock:
"""_release_order_lock() 테스트"""
@pytest.mark.asyncio
async def test_release_success(self):
"""정상적으로 락 해제"""
mock_delete = AsyncMock()
with patch("app.core.redis.delete_key", mock_delete):
from app.services.trade_executor import _release_order_lock
await _release_order_lock("005930", "buy")
mock_delete.assert_called_once_with("order_lock:005930:buy")
@pytest.mark.asyncio
async def test_release_exception_silenced(self):
"""락 해제 실패 시 예외가 무시됨 (TTL 만료로 자동 해제)"""
mock_delete = AsyncMock(side_effect=ConnectionError("Redis down"))
with patch("app.core.redis.delete_key", mock_delete):
from app.services.trade_executor import _release_order_lock
# 예외가 전파되지 않아야 함
await _release_order_lock("005930", "buy")
@pytest.mark.asyncio
async def test_release_key_format(self):
"""해제 키 형식 확인"""
mock_delete = AsyncMock()
with patch("app.core.redis.delete_key", mock_delete):
from app.services.trade_executor import _release_order_lock
await _release_order_lock("TSLA", "sell")
mock_delete.assert_called_once_with("order_lock:TSLA:sell")
# ═══════════════════════════════════════════════════════════════════════════════
# 3. 주문 재시도 테스트
# ═══════════════════════════════════════════════════════════════════════════════
class TestPlaceOrderWithRetry:
"""_place_order_with_retry() 테스트"""
@pytest.mark.asyncio
async def test_domestic_success_first_try(self):
"""국내 주문 — 첫 번째 시도에 성공"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
return_value={"rt_cd": "0", "odno": "12345", "msg1": "정상 처리"}
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=10,
price=72000.0,
)
assert result["rt_cd"] == "0"
assert result["odno"] == "12345"
mock_api.place_order.assert_called_once_with("005930", "buy", 10, 72000.0)
@pytest.mark.asyncio
async def test_overseas_success_first_try(self):
"""해외 주문 — 첫 번째 시도에 성공"""
mock_api = AsyncMock()
mock_api.place_overseas_order = AsyncMock(
return_value={"rt_cd": "0", "odno": "OVS001", "msg1": "success"}
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=False,
stock_code="AAPL",
order_type="buy",
quantity=5,
price=185.50,
exchange_code="NASD",
)
assert result["rt_cd"] == "0"
mock_api.place_overseas_order.assert_called_once_with(
"AAPL", "buy", 5, 185.50, "NASD"
)
@pytest.mark.asyncio
async def test_pending_status_no_retry(self):
"""rt_cd "1"(PENDING) — 재시도 없이 즉시 반환"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
return_value={"rt_cd": "1", "odno": "PND01", "msg1": "접수 처리 중"}
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=10,
price=72000.0,
)
assert result["rt_cd"] == "1"
assert mock_api.place_order.call_count == 1
@pytest.mark.asyncio
async def test_retry_on_error_then_success(self):
"""오류 후 재시도 → 두 번째 시도에 성공"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
side_effect=[
{"rt_cd": "99", "msg1": "시스템 오류"}, # 1차 실패
{"rt_cd": "0", "odno": "12345", "msg1": "정상"}, # 2차 성공
]
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
with patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep:
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=10,
price=72000.0,
max_retries=3,
)
assert result["rt_cd"] == "0"
assert mock_api.place_order.call_count == 2
# 첫 재시도 대기: 1초
mock_sleep.assert_called_once_with(1)
@pytest.mark.asyncio
async def test_max_retries_exhausted(self):
"""최대 재시도 소진 시 마지막 응답 반환"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
return_value={"rt_cd": "99", "msg1": "시스템 오류"}
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
with patch("asyncio.sleep", new_callable=AsyncMock):
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=10,
price=72000.0,
max_retries=3,
)
assert result["rt_cd"] == "99"
assert mock_api.place_order.call_count == 3
@pytest.mark.asyncio
async def test_network_exception_retry(self):
"""네트워크 예외 발생 → 재시도 후 성공"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
side_effect=[
ConnectionError("Connection refused"), # 1차 예외
{"rt_cd": "0", "odno": "12345", "msg1": "정상"}, # 2차 성공
]
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
with patch("asyncio.sleep", new_callable=AsyncMock):
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=10,
price=72000.0,
max_retries=3,
)
assert result["rt_cd"] == "0"
assert mock_api.place_order.call_count == 2
@pytest.mark.asyncio
async def test_all_retries_exception(self):
"""모든 재시도에서 예외 발생 시 오류 응답 반환"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
side_effect=TimeoutError("Request timed out")
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
with patch("asyncio.sleep", new_callable=AsyncMock):
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=10,
price=72000.0,
max_retries=3,
)
assert result["rt_cd"] == "-1"
assert "timed out" in result["msg1"]
assert result["odno"] is None
assert mock_api.place_order.call_count == 3
@pytest.mark.asyncio
async def test_exponential_backoff_timing(self):
"""재시도 대기 시간이 exponential backoff (1→2→4초)를 따르는지 확인"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
return_value={"rt_cd": "99", "msg1": "오류"}
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
with patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep:
from app.services.trade_executor import _place_order_with_retry
await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=10,
price=72000.0,
max_retries=4,
)
# 4번 시도 → sleep 3번 (1차 실패 후 1초, 2차 실패 후 2초, 3차 실패 후 4초)
sleep_calls = [call.args[0] for call in mock_sleep.call_args_list]
assert sleep_calls == [1, 2, 4]
@pytest.mark.asyncio
async def test_single_retry_max(self):
"""max_retries=1 이면 재시도 없이 한 번만 시도"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
return_value={"rt_cd": "99", "msg1": "오류"}
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
with patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep:
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=1,
price=72000.0,
max_retries=1,
)
assert result["rt_cd"] == "99"
assert mock_api.place_order.call_count == 1
mock_sleep.assert_not_called()
@pytest.mark.asyncio
async def test_partial_fill_result(self):
"""부분체결 응답 (rt_cd "0") — 재시도 없이 반환"""
mock_api = AsyncMock()
mock_api.place_order = AsyncMock(
return_value={
"rt_cd": "0",
"odno": "PF001",
"msg1": "부분 체결",
"filled_qty": 5,
"total_qty": 10,
}
)
with patch("app.services.trade_executor.korea_investment_api", mock_api):
from app.services.trade_executor import _place_order_with_retry
result = await _place_order_with_retry(
is_domestic=True,
stock_code="005930",
order_type="buy",
quantity=10,
price=72000.0,
)
assert result["rt_cd"] == "0"
assert result["filled_qty"] == 5
assert mock_api.place_order.call_count == 1
# ═══════════════════════════════════════════════════════════════════════════════
# 4. 신호 분류 (signal_types.py) 테스트
# ═══════════════════════════════════════════════════════════════════════════════
class TestSignalKeywords:
"""BUY_KEYWORDS, SELL_KEYWORDS, STRONG_BUY_KEYWORDS, BLOCK_KEYWORDS 매칭 테스트"""
def test_buy_keywords_contain_all_buy_signals(self):
"""BUY_KEYWORDS가 모든 BuySignal enum 값을 포함하는지 확인"""
for signal in BuySignal:
assert signal.value in BUY_KEYWORDS
def test_sell_keywords_contain_all_sell_signals(self):
"""SELL_KEYWORDS가 모든 SellSignal enum 값을 포함하는지 확인"""
for signal in SellSignal:
assert signal.value in SELL_KEYWORDS
def test_strong_buy_keywords_contain_all_strong_buy_signals(self):
"""STRONG_BUY_KEYWORDS가 모든 StrongBuySignal enum 값을 포함하는지 확인"""
for signal in StrongBuySignal:
assert signal.value in STRONG_BUY_KEYWORDS
def test_block_keywords_contain_all_block_signals(self):
"""BLOCK_KEYWORDS가 모든 BlockSignal enum 값을 포함하는지 확인"""
for signal in BlockSignal:
assert signal.value in BLOCK_KEYWORDS
def test_strong_buy_is_subset_of_buy(self):
"""STRONG_BUY는 BUY의 부분집합이어야 함"""
for kw in STRONG_BUY_KEYWORDS:
assert kw in BUY_KEYWORDS, f"강한 매수 신호 '{kw}'가 매수 키워드에 없음"
def test_buy_sell_no_overlap(self):
"""매수·매도 키워드 간 중복이 없어야 함"""
overlap = set(BUY_KEYWORDS) & set(SELL_KEYWORDS)
assert len(overlap) == 0, f"매수·매도 키워드 중복: {overlap}"
def test_block_buy_no_overlap(self):
"""차단·매수 키워드 간 중복이 없어야 함"""
overlap = set(BLOCK_KEYWORDS) & set(BUY_KEYWORDS)
assert len(overlap) == 0, f"차단·매수 키워드 중복: {overlap}"
def test_buy_keywords_count(self):
"""BUY_KEYWORDS 개수가 BuySignal enum 멤버 수와 일치"""
assert len(BUY_KEYWORDS) == len(BuySignal)
def test_sell_keywords_count(self):
"""SELL_KEYWORDS 개수가 SellSignal enum 멤버 수와 일치"""
assert len(SELL_KEYWORDS) == len(SellSignal)
def test_specific_buy_keyword_matching(self):
"""특정 매수 키워드 매칭 테스트"""
test_description = "RSI 바닥 탈출 반등"
assert test_description in BUY_KEYWORDS
def test_specific_sell_keyword_matching(self):
"""특정 매도 키워드 매칭 테스트"""
test_description = "RSI 과매수"
assert test_description in SELL_KEYWORDS
def test_specific_block_keyword_matching(self):
"""특정 차단 키워드 매칭 테스트"""
test_descriptions = ["이격도 과열", "매수금지", "급등 종목 추격 금지", "급등과열"]
for desc in test_descriptions:
assert desc in BLOCK_KEYWORDS, f"'{desc}'가 BLOCK_KEYWORDS에 없음"
def test_specific_strong_buy_keyword_matching(self):
"""특정 강한 매수 키워드 매칭 테스트"""
strong_signals = ["RSI 바닥 탈출 반등", "볼린저 하한선 터치", "눌림목 진입 매수타점", "정배열 눌림목 매수"]
for desc in strong_signals:
assert desc in STRONG_BUY_KEYWORDS, f"'{desc}'가 STRONG_BUY_KEYWORDS에 없음"
def test_unknown_signal_not_in_keywords(self):
"""알 수 없는 신호 문자열은 어떤 키워드 목록에도 포함되지 않음"""
unknown = "존재하지 않는 신호"
assert unknown not in BUY_KEYWORDS
assert unknown not in SELL_KEYWORDS
assert unknown not in STRONG_BUY_KEYWORDS
assert unknown not in BLOCK_KEYWORDS
def test_keyword_signal_classification(self):
"""신호 문자열로 매수/매도/차단 분류가 올바르게 동작하는지 확인"""
test_cases = [
("정배열 눌림목 매수", "buy"),
("RSI 과매수", "sell"),
("이격도 과열", "block"),
("골든크로스", "buy"),
("데드크로스", "sell"),
("매수금지", "block"),
]
for signal, expected_type in test_cases:
if expected_type == "buy":
assert signal in BUY_KEYWORDS, f"'{signal}'이 BUY_KEYWORDS에 없음"
elif expected_type == "sell":
assert signal in SELL_KEYWORDS, f"'{signal}'이 SELL_KEYWORDS에 없음"
elif expected_type == "block":
assert signal in BLOCK_KEYWORDS, f"'{signal}'이 BLOCK_KEYWORDS에 없음"
def test_enum_string_comparison(self):
"""Enum이 str 서브클래스이므로 직접 문자열 비교 가능"""
assert BuySignal.골든크로스 == "골든크로스"
assert SellSignal.데드크로스 == "데드크로스"
assert BlockSignal.매수금지 == "매수금지"
assert StrongBuySignal.RSI바닥탈출 == "RSI 바닥 탈출 반등"