57 lines
2.7 KiB
Python
57 lines
2.7 KiB
Python
from app import holdings_intel as hi
|
|
|
|
def test_get_holdings_merges_price_and_pnl(monkeypatch):
|
|
monkeypatch.setattr(hi.db, "get_all_portfolio", lambda: [
|
|
{"id": 1, "broker": "kis", "ticker": "005930", "name": "삼성전자",
|
|
"quantity": 10, "avg_price": 70000, "purchase_price": 70000},
|
|
{"id": 2, "broker": "kis", "ticker": "AAPL", "name": "Apple",
|
|
"quantity": 5, "avg_price": 200, "purchase_price": 200},
|
|
])
|
|
monkeypatch.setattr(hi.price_fetcher, "get_current_prices",
|
|
lambda tickers: {"005930": 77000}) # AAPL 미조회(비KRX)
|
|
monkeypatch.setattr(hi, "_krx_tickers", lambda: {"005930"})
|
|
hs = hi.get_holdings()
|
|
s = {h["ticker"]: h for h in hs}
|
|
assert s["005930"]["is_krx"] is True
|
|
assert round(s["005930"]["pnl_rate"], 1) == 10.0 # (77000-70000)/70000
|
|
assert s["AAPL"]["is_krx"] is False # KRX 외
|
|
|
|
|
|
def test_get_holdings_zero_avg_price(monkeypatch):
|
|
"""avg_price=0인 종목은 pnl_rate가 None이어야 한다 (ZeroDivisionError 없음)."""
|
|
monkeypatch.setattr(hi.db, "get_all_portfolio", lambda: [
|
|
{"id": 1, "broker": "kis", "ticker": "005930", "name": "삼성전자",
|
|
"quantity": 10, "avg_price": 0, "purchase_price": 0},
|
|
])
|
|
monkeypatch.setattr(hi.price_fetcher, "get_current_prices",
|
|
lambda tickers: {"005930": 80000})
|
|
monkeypatch.setattr(hi, "_krx_tickers", lambda: {"005930"})
|
|
hs = hi.get_holdings()
|
|
assert hs[0]["pnl_rate"] is None
|
|
|
|
|
|
def test_get_holdings_empty_portfolio(monkeypatch):
|
|
"""포트폴리오가 비어있으면 빈 리스트를 반환하고 가격 조회를 호출하지 않는다."""
|
|
monkeypatch.setattr(hi.db, "get_all_portfolio", lambda: [])
|
|
called = []
|
|
monkeypatch.setattr(hi.price_fetcher, "get_current_prices",
|
|
lambda tickers: called.append(tickers) or {})
|
|
monkeypatch.setattr(hi, "_krx_tickers", lambda: set())
|
|
result = hi.get_holdings()
|
|
assert result == []
|
|
assert called == [] # get_current_prices must NOT have been called
|
|
|
|
|
|
def test_get_holdings_price_missing(monkeypatch):
|
|
"""prices dict에 ticker가 없으면 current_price와 pnl_rate는 None이다."""
|
|
monkeypatch.setattr(hi.db, "get_all_portfolio", lambda: [
|
|
{"id": 1, "broker": "kis", "ticker": "000660", "name": "SK하이닉스",
|
|
"quantity": 5, "avg_price": 150000, "purchase_price": 150000},
|
|
])
|
|
monkeypatch.setattr(hi.price_fetcher, "get_current_prices",
|
|
lambda tickers: {}) # 가격 없음
|
|
monkeypatch.setattr(hi, "_krx_tickers", lambda: {"000660"})
|
|
hs = hi.get_holdings()
|
|
assert hs[0]["current_price"] is None
|
|
assert hs[0]["pnl_rate"] is None
|