Files
portfolio-hub/tests/test_portfolio_ownership.py
T
genichin e2226e28b6 feat: implement asset catalog database foundation (BAT-001, REQ-009/011/014)
Asset Catalog Model Implementation (BAT-001):
- Introduce assets table with UUID PK, symbol UNIQUE, markets TEXT[] array
- Define MarketCode enum (KRX, NXT, SOR, NASDAQ, NYSE, UPBIT, BITHUMB)
- Add Asset domain model with catalog properties
- Implement asset CRUD protocols in portfolio_repository
- Add PostgreSQL asset CRUD operations with GIN index on markets

Portfolio Model Refactoring (REQ-011):
- Add portfolios.asset_id UUID FK to assets(asset_id) ON DELETE RESTRICT
- Remove portfolios.symbol and portfolios.market columns
- Update Portfolio domain model to reference asset_id instead of symbol/market
- Refactor all portfolio queries to JOIN assets catalog
- Update all repository methods to use asset references

Data Migration (REQ-014):
- Create 20260519_0017 Alembic revision for assets table creation
- Create 20260519_0018 Alembic revision for atomic data migration:
  * Extract unique symbol combinations from portfolios
  * Aggregate markets using ARRAY_AGG(DISTINCT market)
  * Populate assets catalog with extracted data
  * Update portfolios.asset_id to reference new assets
  * Remove legacy symbol/market columns in single transaction
- Implement migration with rollback support

Requirements Approved (REQ-001~008):
- REQ-001~008 transitioned from Proposed to Approved
- Complete tag model requirement set with implementation readiness

New Requirements Approved (REQ-009~015):
- REQ-009: assets table schema (approved, included in BAT-001)
- REQ-010: admin asset catalog CRUD (approved, future BAT-002)
- REQ-011: portfolios asset_id FK (approved, included in BAT-001)
- REQ-012: portfolio create catalog validation (approved, future BAT-002)
- REQ-013: GET /v1/assets token branching (approved, future BAT-002)
- REQ-014: portfolios data migration (approved, included in BAT-001)
- REQ-015: asset catalog baseline docs (approved)

Code Changes:
- app/domain/models.py: Add Asset model, MarketCode enum, Portfolio asset_id FK
- app/repositories/portfolio_repository.py: Define asset CRUD protocol
- app/repositories/postgres.py: Implement asset operations with full CRUD
- app/api/v1_assets.py: Remove symbol/market direct references
- app/cli/commands/portfolio.py: Update portfolio commands for asset references
- app/schemas/portfolio.py: Update portfolio schema with asset_id
- All portfolio operations throughout codebase: Use asset references

Testing:
- Add test_asset_catalog.py for asset CRUD operations
- Verify REQ-009 AC-1~5 (asset catalog creation, lookup, uniqueness)
- Verify REQ-011 AC-1~5 (FK constraint, portfolio asset reference)
- Verify REQ-014 AC-1~6 (migration atomicity, data correctness, rollback)
- Update existing tests for asset model usage

Documentation:
- Create BAT-001 batch documents (planning, design, implementation, verification)
- Update dcy-001 with implementation details and confirmed architecture
- Add 8 new requirement documents (REQ-009~015)
- Update docs/discovery/index.md with batch entry

Impact:
- Database: assets catalog table, portfolios refactored to reference assets
- Migration: 2 new Alembic revisions (0017 assets, 0018 portfolio migration)
- API: Symbol/market now accessed through asset references
- CLI: Portfolio commands require asset reference pattern
- All existing portfolio data preserved and correctly migrated
2026-05-19 15:59:20 +00:00

173 lines
6.0 KiB
Python

from __future__ import annotations
from datetime import datetime, timezone
from fastapi.testclient import TestClient
import app.api.portfolios as portfolios_api
import app.core.auth as auth_core
from app.core.config import get_settings
from app.core.security import hash_token
from app.domain.models import LedgerEntry, Portfolio, StrategySet, TokenPrincipal
from app.main import app
class FakeRepo:
def __init__(self, *, portfolio: Portfolio, principals: dict[str, TokenPrincipal]) -> None:
self._portfolio = portfolio
self._principals = principals
self._strategy = StrategySet(id="set-1", name="target_value", config="{}", nick="target_value:demo")
def close(self) -> None:
return None
def list_users(self):
return []
def get_token_principal(self, token_hash: str):
return self._principals.get(token_hash)
def get(self, portfolio_id: str) -> Portfolio:
if self._portfolio.portfolio_id != portfolio_id:
raise ValueError("포트폴리오를 찾을 수 없습니다")
return self._portfolio
def list_recent_trades(self, portfolio_id: str, limit: int = 5) -> list[LedgerEntry]:
return []
def list_portfolios(
self,
*,
broker: str | None = None,
status: str | None = None,
owner_user_id: str | None = None,
include_tags: list[str] | None = None,
exclude_tags: list[str] | None = None,
match_mode: str | None = None,
):
if owner_user_id is not None and self._portfolio.owner_user_id != owner_user_id:
return []
return [self._portfolio]
def add_tag(self, portfolio_id: str, *, tag: str):
raise NotImplementedError()
def list_tags(self, portfolio_id: str):
return []
def remove_tag(self, portfolio_id: str, *, tag: str) -> None:
raise NotImplementedError()
def get_strategy_set(self, id: str):
if id == self._strategy.id:
return self._strategy
return None
def _portfolio(owner_user_id: str) -> Portfolio:
return Portfolio(
portfolio_id="p1",
broker="kis",
status="enabled",
name="Samsung Electronics",
symbol="005930",
owner_user_id=owner_user_id,
cash_balance=1_000_000.0,
asset_quantity=1.0,
price=70_000.0,
profit_buffer=0.0,
active_strategy_id="set-1",
avabile_strategies=["set-1"],
created_at=datetime.now(timezone.utc),
updated_at=datetime.now(timezone.utc),
)
def _configure_client(monkeypatch, repo: FakeRepo) -> TestClient:
monkeypatch.setenv("PORTFOLIOHUB_DB_ENABLED", "true")
monkeypatch.delenv("PORTFOLIOHUB_READ_TOKENS", raising=False)
monkeypatch.delenv("PORTFOLIOHUB_TRADE_WRITE_TOKENS", raising=False)
monkeypatch.delenv("PORTFOLIOHUB_ADMIN_TOKENS", raising=False)
get_settings.cache_clear()
app.dependency_overrides.clear()
monkeypatch.setattr(portfolios_api, "get_portfolio_repository_from_settings", lambda settings: repo)
monkeypatch.setattr(auth_core, "get_portfolio_repository_from_settings", lambda settings: repo)
return TestClient(app)
def test_owner_can_read_owned_portfolio_on_db_auth(monkeypatch) -> None:
token = "owner-db-token"
principal = TokenPrincipal(
token_id="t1",
user_id="owner-1",
permission="read",
token_type="client",
)
repo = FakeRepo(portfolio=_portfolio("owner-1"), principals={hash_token(token): principal})
client = _configure_client(monkeypatch, repo)
response = client.get("/portfolios/p1", headers={"Authorization": f"Bearer {token}"})
app.dependency_overrides.clear()
assert response.status_code == 200
assert response.json()["portfolio"]["owner_user_id"] == "owner-1"
def test_non_owner_gets_403_on_db_auth(monkeypatch) -> None:
token = "other-db-token"
principal = TokenPrincipal(
token_id="t2",
user_id="other-user",
permission="read",
token_type="client",
)
repo = FakeRepo(portfolio=_portfolio("owner-1"), principals={hash_token(token): principal})
client = _configure_client(monkeypatch, repo)
response = client.get("/portfolios/p1", headers={"Authorization": f"Bearer {token}"})
app.dependency_overrides.clear()
assert response.status_code == 403
assert response.json()["detail"] == "Portfolio ownership mismatch"
def test_owner_bound_bot_token_can_read_owned_portfolio(monkeypatch) -> None:
token = "owner-bot-token"
principal = TokenPrincipal(
token_id="t-bot-1",
user_id="owner-1",
permission="read",
token_type="service",
)
repo = FakeRepo(portfolio=_portfolio("owner-1"), principals={hash_token(token): principal})
client = _configure_client(monkeypatch, repo)
response = client.get("/portfolios/p1", headers={"Authorization": f"Bearer {token}"})
app.dependency_overrides.clear()
assert response.status_code == 200
assert response.json()["portfolio"]["owner_user_id"] == "owner-1"
def test_db_enabled_env_token_without_user_context_is_rejected(monkeypatch) -> None:
repo = FakeRepo(portfolio=_portfolio("owner-1"), principals={})
monkeypatch.setenv("PORTFOLIOHUB_DB_ENABLED", "true")
monkeypatch.setenv("PORTFOLIOHUB_TRADE_WRITE_TOKENS", "trade-env-token")
monkeypatch.delenv("PORTFOLIOHUB_READ_TOKENS", raising=False)
monkeypatch.delenv("PORTFOLIOHUB_ADMIN_TOKENS", raising=False)
get_settings.cache_clear()
app.dependency_overrides.clear()
monkeypatch.setattr(portfolios_api, "get_portfolio_repository_from_settings", lambda settings: repo)
monkeypatch.setattr(auth_core, "get_portfolio_repository_from_settings", lambda settings: repo)
client = TestClient(app)
response = client.post(
"/portfolios",
headers={"Authorization": "Bearer trade-env-token"},
json={"name": "new-1", "asset_id": "00000000-0000-0000-0000-000000000001"},
)
app.dependency_overrides.clear()
assert response.status_code == 403
assert response.json()["detail"] == "Ownership context is required"