Files
portfolio-hub/tests/test_auth.py
T

66 lines
2.2 KiB
Python

from __future__ import annotations
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.main import app
def _client_with_tokens() -> TestClient:
get_settings.cache_clear()
app.dependency_overrides.clear()
return TestClient(app)
def test_read_route_requires_token(monkeypatch) -> None:
monkeypatch.setenv("PORTFOLIOHUB_DB_ENABLED", "false")
monkeypatch.setenv("PORTFOLIOHUB_READ_TOKENS", "read-token")
get_settings.cache_clear()
client = _client_with_tokens()
response = client.get("/portfolios")
assert response.status_code == 401
assert response.json()["detail"] == "Missing bearer token"
def test_read_route_accepts_read_token(monkeypatch) -> None:
monkeypatch.setenv("PORTFOLIOHUB_DB_ENABLED", "false")
monkeypatch.setenv("PORTFOLIOHUB_READ_TOKENS", "read-token")
get_settings.cache_clear()
client = _client_with_tokens()
response = client.get("/portfolios", headers={"Authorization": "Bearer read-token"})
assert response.status_code == 501
assert response.json()["detail"] == "Portfolio persistence is not implemented yet"
def test_trade_route_rejects_read_token(monkeypatch) -> None:
monkeypatch.setenv("PORTFOLIOHUB_DB_ENABLED", "false")
monkeypatch.setenv("PORTFOLIOHUB_READ_TOKENS", "read-token")
monkeypatch.setenv("PORTFOLIOHUB_TRADE_WRITE_TOKENS", "trade-token")
get_settings.cache_clear()
client = _client_with_tokens()
response = client.post(
"/portfolios/p1/buy",
headers={"Authorization": "Bearer read-token"},
json={"quantity": 1, "price": 1000, "fee": 0, "tax": 0, "note": ""},
)
assert response.status_code == 403
assert response.json()["detail"] == "Insufficient permission"
def test_admin_route_accepts_admin_token(monkeypatch) -> None:
monkeypatch.setenv("PORTFOLIOHUB_DB_ENABLED", "false")
monkeypatch.setenv("PORTFOLIOHUB_ADMIN_TOKENS", "admin-token")
get_settings.cache_clear()
client = _client_with_tokens()
response = client.delete("/portfolios/p1", headers={"Authorization": "Bearer admin-token"})
assert response.status_code == 501
assert response.json()["detail"] == "Portfolio persistence is not implemented yet"