"""9회차 D 그룹(KIS 계층) 회귀 테스트. D-1 get_balance_all_v2 잔고 연속조회 / D-2 청산 경로 조회의 서킷브레이커 게이트 면제 / D-3 get_todays_orders_v2 실패=None. 목킹은 공통 종단(_make_request / http client)에 건다. 실 KIS 호출 0건. """ import asyncio import pytest from app.core.config import settings from app.services import korea_investment_api as kia from app.services.utils import CircuitBreakerState BAL_EP = "/uapi/domestic-stock/v1/trading/inquire-balance" PRICE_EP = "/uapi/domestic-stock/v1/quotations/inquire-price" CCLD_EP = "/uapi/domestic-stock/v1/trading/inquire-daily-ccld" DAILY_EP = "/uapi/domestic-stock/v1/quotations/inquire-daily-price" # [R9 B 그룹 목킹 보정] conftest 가 get_balance_all_v2·get_todays_orders_v2 를 클래스 단위로 차단한다. # 이 파일은 그 메서드 자체를 검증하므로 import 시점 원본을 테스트마다 되돌린다(test_infra_security_round2 # 와 같은 패턴). 내부 전송(_make_request)은 각 테스트가 목킹하고 토큰·소켓 차단은 그대로 유효하다. _ORIG_GET_BALANCE_ALL_V2 = kia.KoreaInvestmentAPI.__dict__["get_balance_all_v2"] _ORIG_GET_TODAYS_ORDERS_V2 = kia.KoreaInvestmentAPI.__dict__["get_todays_orders_v2"] @pytest.fixture(autouse=True) def _restore_methods_under_test(monkeypatch): monkeypatch.setattr(kia.KoreaInvestmentAPI, "get_balance_all_v2", _ORIG_GET_BALANCE_ALL_V2) monkeypatch.setattr(kia.KoreaInvestmentAPI, "get_todays_orders_v2", _ORIG_GET_TODAYS_ORDERS_V2) def _bare_api(): api = kia.KoreaInvestmentAPI.__new__(kia.KoreaInvestmentAPI) api.base_url = "https://openapivts.example" api.account_number = "1234567801" return api def _row(code): return {"pdno": code, "hldg_qty": "1"} def _page(codes, nk="", fk="", rt="0"): return {"rt_cd": rt, "msg_cd": "M", "msg1": "ok", "output1": [_row(c) for c in codes], "output2": [{"tot_evlu_amt": "1000"}], "ctx_area_fk100": fk, "ctx_area_nk100": nk} class _Seq: """_make_request 대체 — 준비된 (result, headers) 또는 예외를 순서대로. 소진 시 예외.""" def __init__(self, items): self.items = list(items) self.calls = [] async def __call__(self, method, endpoint, tr_id, extra_headers=None, **kwargs): self.calls.append({"endpoint": endpoint, "extra_headers": extra_headers, "params": kwargs.get("params")}) if not self.items: raise AssertionError("unexpected extra _make_request call") it = self.items.pop(0) if isinstance(it, BaseException): raise it return it # ── D-1 ────────────────────────────────────────────────────────────────── @pytest.mark.asyncio async def test_balance_single_page(monkeypatch): api = _bare_api() seq = _Seq([(_page(["A", "B"]), {"tr_cont": "D"})]) monkeypatch.setattr(api, "_make_request", seq, raising=False) out = await api.get_balance_all_v2() assert [r["pdno"] for r in out["output1"]] == ["A", "B"] assert out["_pages"] == 1 and "_partial" not in out assert out["output2"] == [{"tot_evlu_amt": "1000"}] assert len(seq.calls) == 1 and seq.calls[0]["endpoint"] == BAL_EP @pytest.mark.asyncio async def test_balance_three_pages_merge_dedupe(monkeypatch): api = _bare_api() p1 = _page(["A", "B"], nk="N1", fk="F1") p2 = _page(["B", "C"], nk="N2", fk="F2") p2["output2"] = [{"tot_evlu_amt": "999"}] p3 = _page(["D"]) seq = _Seq([(p1, {"tr_cont": "F"}), (p2, {"tr_cont": "M"}), (p3, {"tr_cont": "D"})]) monkeypatch.setattr(api, "_make_request", seq, raising=False) out = await api.get_balance_all_v2() assert [r["pdno"] for r in out["output1"]] == ["A", "B", "C", "D"] assert out["_pages"] == 3 and "_partial" not in out assert out["output2"] == [{"tot_evlu_amt": "1000"}] # 첫 페이지 것 assert seq.calls[0]["extra_headers"] is None assert seq.calls[1]["extra_headers"] == {"tr_cont": "N"} assert seq.calls[1]["params"]["CTX_AREA_NK100"] == "N1" assert seq.calls[1]["params"]["CTX_AREA_FK100"] == "F1" assert seq.calls[2]["params"]["CTX_AREA_NK100"] == "N2" @pytest.mark.asyncio async def test_balance_second_page_exception_partial(monkeypatch): api = _bare_api() seq = _Seq([(_page(["A"], nk="N1"), {"tr_cont": "F"}), RuntimeError("boom")]) monkeypatch.setattr(api, "_make_request", seq, raising=False) out = await api.get_balance_all_v2() assert out["_partial"] is True and out["_pages"] == 1 assert [r["pdno"] for r in out["output1"]] == ["A"] @pytest.mark.asyncio async def test_balance_second_page_rt_cd_fail_partial(monkeypatch): api = _bare_api() seq = _Seq([(_page(["A"], nk="N1"), {"tr_cont": "F"}), (_page([], rt="1"), {})]) monkeypatch.setattr(api, "_make_request", seq, raising=False) out = await api.get_balance_all_v2() assert out["_partial"] is True and out["_pages"] == 1 @pytest.mark.asyncio async def test_balance_missing_ctx_is_partial(monkeypatch): api = _bare_api() seq = _Seq([(_page(["A"], nk=""), {"tr_cont": "M"})]) monkeypatch.setattr(api, "_make_request", seq, raising=False) out = await api.get_balance_all_v2() assert out["_partial"] is True and len(seq.calls) == 1 @pytest.mark.asyncio async def test_balance_max_pages_cap(monkeypatch): api = _bare_api() cap = settings.KIS_BALANCE_MAX_PAGES items = [(_page([f"S{i}"], nk=f"N{i}"), {"tr_cont": "M"}) for i in range(cap + 3)] seq = _Seq(items) monkeypatch.setattr(api, "_make_request", seq, raising=False) out = await api.get_balance_all_v2() assert len(seq.calls) == cap assert out["_pages"] == cap and out["_partial"] is True assert len(out["output1"]) == cap @pytest.mark.asyncio async def test_balance_first_page_failure_same_as_get_balance(monkeypatch): api = _bare_api() bad = _page([], rt="1") monkeypatch.setattr(api, "_make_request", _Seq([(bad, {"tr_cont": "F"})]), raising=False) out = await api.get_balance_all_v2() assert out is bad and "_pages" not in out monkeypatch.setattr(api, "_make_request", _Seq([RuntimeError("down")]), raising=False) with pytest.raises(RuntimeError): await api.get_balance_all_v2() @pytest.mark.asyncio async def test_balance_params_match_get_balance(monkeypatch): """첫 페이지 요청 파라미터가 기존 get_balance() 와 동일해야 한다(get_balance 는 conftest 가 차단 → 고정값 비교).""" api = _bare_api() seq = _Seq([(_page(["A"]), {})]) monkeypatch.setattr(api, "_make_request", seq, raising=False) await api.get_balance_all_v2() assert seq.calls[0]["params"] == { "CANO": "12345678", "ACNT_PRDT_CD": "01", "AFHR_FLPR_YN": "N", "OFL_YN": "", "INQR_DVSN": "02", "UNPR_DVSN": "01", "FUND_STTL_ICLD_YN": "N", "FNCG_AMT_AUTO_RDPT_YN": "N", "PRCS_DVSN": "01", "CTX_AREA_FK100": "", "CTX_AREA_NK100": "", } @pytest.mark.asyncio async def test_balance_unmocked_hits_conftest_block(monkeypatch): """목킹 없이 호출하면 conftest 의 _get_access_token 차단(BaseException)이 그대로 올라와야 한다.""" api, client = _net_api(monkeypatch, _Resp(200, {"rt_cd": "0"}), patch_token=False) api.account_number = "1234567801" with pytest.raises(BaseException) as ei: await api.get_balance_all_v2() assert type(ei.value).__name__ == "KISCallBlocked" assert client.calls == [] # ── D-2 ────────────────────────────────────────────────────────────────── class _Resp: def __init__(self, status=200, body=None): self.status_code, self._b, self.headers, self.text = status, body or {}, {}, "" def json(self): return self._b class _Client: def __init__(self, resp): self.resp, self.calls = resp, [] async def request(self, method, url, **k): self.calls.append(url) if isinstance(self.resp, BaseException): raise self.resp return self.resp def _net_api(monkeypatch, resp, patch_token=True): api = kia.KoreaInvestmentAPI.__new__(kia.KoreaInvestmentAPI) api.circuit_breaker = kia.CircuitBreaker(failure_threshold=2, recovery_timeout=120) api.monitor = kia.APICallMonitor() api.semaphore = asyncio.Semaphore(2) api._throttle_lock = asyncio.Lock() api.last_request_time = None api.min_request_interval = 0 api.max_retries = 0 api.retry_delay = 0 api.retry_backoff = 1 api.timeout = 1 api.app_key = api.app_secret = "x" api.base_url = "http://x" client = _Client(resp) async def _tok(*a, **k): return "tok" async def _cl(): return client if patch_token: monkeypatch.setattr(api, "_get_access_token", _tok, raising=False) monkeypatch.setattr(api, "_get_http_client", _cl, raising=False) return api, client def _open(api): for _ in range(api.circuit_breaker.failure_threshold): api.circuit_breaker.record_failure() assert api.circuit_breaker.state == CircuitBreakerState.OPEN @pytest.mark.asyncio @pytest.mark.parametrize("ep", [BAL_EP, PRICE_EP, CCLD_EP]) async def test_exempt_reads_pass_gate_when_open(monkeypatch, ep): api, client = _net_api(monkeypatch, _Resp(200, {"rt_cd": "0"})) _open(api) out, _ = await api._make_request("GET", ep, "X") assert out["rt_cd"] == "0" and len(client.calls) == 1 @pytest.mark.asyncio async def test_non_exempt_read_still_blocked(monkeypatch): api, client = _net_api(monkeypatch, _Resp(200, {"rt_cd": "0"})) _open(api) with pytest.raises(Exception, match="Circuit breaker open"): await api._make_request("GET", DAILY_EP, "X") assert client.calls == [] @pytest.mark.asyncio async def test_exempt_success_while_open_keeps_breaker_open(monkeypatch): """[D-2b] OPEN 중 면제 성공은 record_success 하지 않는다 → 여전히 OPEN.""" api, client = _net_api(monkeypatch, _Resp(200, {"rt_cd": "0"})) _open(api) cnt = api.circuit_breaker.failure_count out, _ = await api._make_request("GET", PRICE_EP, "X") assert out["rt_cd"] == "0" and len(client.calls) == 1 assert api.circuit_breaker.state == CircuitBreakerState.OPEN assert api.circuit_breaker.failure_count == cnt @pytest.mark.asyncio async def test_exempt_failure_while_open_not_recorded(monkeypatch): """[D-2b] OPEN 중 면제 실패는 last_failure_time·failure_count 를 건드리지 않는다.""" api, _ = _net_api(monkeypatch, RuntimeError("conn reset")) _open(api) api.circuit_breaker.last_failure_time -= 50 # 경과 시간 표시 lft, cnt = api.circuit_breaker.last_failure_time, api.circuit_breaker.failure_count with pytest.raises(RuntimeError): await api._make_request("GET", BAL_EP, "X") assert api.circuit_breaker.last_failure_time == lft assert api.circuit_breaker.failure_count == cnt assert api.circuit_breaker.state == CircuitBreakerState.OPEN @pytest.mark.asyncio async def test_exempt_does_not_consume_half_open_probe(monkeypatch): """[D-2b] 복구 대기 경과 후에도 면제 호출은 HALF_OPEN 전이를 일으키지 않고 집계도 없다.""" api, _ = _net_api(monkeypatch, _Resp(200, {"rt_cd": "0"})) _open(api) api.circuit_breaker.last_failure_time -= api.circuit_breaker.recovery_timeout + 1 await api._make_request("GET", CCLD_EP, "X") assert api.circuit_breaker.state == CircuitBreakerState.OPEN @pytest.mark.asyncio async def test_exempt_failure_while_closed_is_counted(monkeypatch): """[D-2b] CLOSED 중 면제 실패는 기존대로 집계(장애 감지 유지).""" api, _ = _net_api(monkeypatch, RuntimeError("conn reset")) assert api.circuit_breaker.state == CircuitBreakerState.CLOSED with pytest.raises(RuntimeError): await api._make_request("GET", BAL_EP, "X") assert api.circuit_breaker.failure_count == 1 with pytest.raises(RuntimeError): await api._make_request("GET", PRICE_EP, "X") assert api.circuit_breaker.state == CircuitBreakerState.OPEN # threshold=2 @pytest.mark.asyncio async def test_non_exempt_half_open_probe_success_closes(monkeypatch): """[D-2b] OPEN 해제는 비면제 조회의 HALF_OPEN 프로브 성공으로만.""" api, client = _net_api(monkeypatch, _Resp(200, {"rt_cd": "0"})) _open(api) api.circuit_breaker.last_failure_time -= api.circuit_breaker.recovery_timeout + 1 await api._make_request("GET", DAILY_EP, "X") assert len(client.calls) == 1 assert api.circuit_breaker.state == CircuitBreakerState.CLOSED @pytest.mark.asyncio async def test_uncounted_flag_does_not_leak_to_next_call(monkeypatch): """면제 호출 후 컨텍스트 플래그가 초기화돼 이어지는 비면제 실패는 집계된다.""" api, client = _net_api(monkeypatch, _Resp(200, {"rt_cd": "0"})) _open(api) await api._make_request("GET", PRICE_EP, "X") assert kia._BREAKER_UNCOUNTED.get() is False api.circuit_breaker.last_failure_time -= api.circuit_breaker.recovery_timeout + 1 client.resp = RuntimeError("down") lft = api.circuit_breaker.last_failure_time with pytest.raises(RuntimeError): await api._make_request("GET", DAILY_EP, "X") # HALF_OPEN 프로브 실패 → 집계 assert api.circuit_breaker.last_failure_time > lft def test_exempt_set_excludes_orders(): assert set(kia.KoreaInvestmentAPI._CIRCUIT_EXEMPT_READ_ENDPOINTS).isdisjoint( kia.KoreaInvestmentAPI._NON_IDEMPOTENT_ENDPOINTS) assert kia.DAILY_CCLD_ENDPOINT in kia.KoreaInvestmentAPI._CIRCUIT_EXEMPT_READ_ENDPOINTS # ── D-3 ────────────────────────────────────────────────────────────────── def _ccld(monkeypatch, api, item): async def _f(*a, **k): if isinstance(item, BaseException): raise item return item, {} monkeypatch.setattr(api, "_daily_ccld_fetch_v2", _f, raising=False) @pytest.mark.asyncio async def test_orders_v2_success_list(monkeypatch): api = _bare_api() _ccld(monkeypatch, api, {"rt_cd": "0", "output1": [{"odno": "1"}]}) assert await api.get_todays_orders_v2("005930") == [{"odno": "1"}] _ccld(monkeypatch, api, {"rt_cd": "0", "output1": []}) assert await api.get_todays_orders_v2() == [] _ccld(monkeypatch, api, {"rt_cd": "0", "output1": {"odno": "2"}}) assert await api.get_todays_orders_v2() == [{"odno": "2"}] @pytest.mark.asyncio async def test_orders_v2_rt_cd_fail_none_legacy_empty(monkeypatch): api = _bare_api() _ccld(monkeypatch, api, {"rt_cd": "1", "msg_cd": "X"}) assert await api.get_todays_orders_v2() is None assert await api._get_todays_orders_impl(strict=False) == [] @pytest.mark.asyncio async def test_orders_v2_exception_none_legacy_empty(monkeypatch): api = _bare_api() _ccld(monkeypatch, api, RuntimeError("timeout")) assert await api.get_todays_orders_v2() is None assert await api._get_todays_orders_impl(strict=False) == [] @pytest.mark.asyncio async def test_orders_v2_unparseable_none(monkeypatch): api = _bare_api() _ccld(monkeypatch, api, {"rt_cd": "0", "output1": "garbage"}) assert await api.get_todays_orders_v2() is None assert await api._get_todays_orders_impl(strict=False) == ["garbage"] # 기존 동작 불변 _ccld(monkeypatch, api, ["not-a-dict"]) assert await api.get_todays_orders_v2() is None def test_legacy_get_todays_orders_delegates_non_strict(): import inspect src = inspect.getsource(kia.KoreaInvestmentAPI._get_todays_orders_impl) assert "None if strict else []" in src