127 lines
5.4 KiB
Python
127 lines
5.4 KiB
Python
|
|
from datetime import datetime
|
||
|
|
|
||
|
|
import httpx
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from app.dashboard import pyramid_rows
|
||
|
|
from app.models import Account
|
||
|
|
from app.worldquant import WqClient, WqError
|
||
|
|
|
||
|
|
|
||
|
|
def pyramid(**extra):
|
||
|
|
return {"category": {"id": "analyst", "name": "Analyst"}, "region": "USA", "delay": 1, **extra}
|
||
|
|
|
||
|
|
|
||
|
|
async def test_pyramid_read_paths_and_404_fallback(settings):
|
||
|
|
calls = []
|
||
|
|
|
||
|
|
def upstream(request):
|
||
|
|
calls.append(request)
|
||
|
|
assert request.method == "GET"
|
||
|
|
if request.url.path.endswith("pyramid-multipliers"):
|
||
|
|
return httpx.Response(200, json={"pyramids": [pyramid(multiplier=1.3)]})
|
||
|
|
if request.url.path != "/activities/pyramid-alphas":
|
||
|
|
return httpx.Response(404)
|
||
|
|
return httpx.Response(200, json={"pyramids": [pyramid(alphaCount=0)]})
|
||
|
|
|
||
|
|
client = WqClient(settings, transport=httpx.MockTransport(upstream))
|
||
|
|
client.credentials, client.authenticated = ("test@example.com", "test-only"), True
|
||
|
|
try:
|
||
|
|
assert (await client.get_pyramid_multipliers())["pyramids"][0]["multiplier"] == 1.3
|
||
|
|
data = await client.get_pyramid_alphas("2026-07-01", "2026-07-31")
|
||
|
|
assert data["pyramids"][0]["alphaCount"] == 0
|
||
|
|
assert [r.url.path for r in calls] == [
|
||
|
|
"/users/self/activities/pyramid-multipliers", "/users/self/activities/pyramid-alphas",
|
||
|
|
"/users/self/pyramid/alphas", "/activities/pyramid-alphas",
|
||
|
|
]
|
||
|
|
for request in calls[1:]:
|
||
|
|
assert dict(request.url.params) == {
|
||
|
|
"startDate": "2026-07-01", "endDate": "2026-07-31",
|
||
|
|
}
|
||
|
|
finally:
|
||
|
|
await client.close()
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize("status,code,expected_calls", [(403, "access_denied", 1), (404, "not_found", 3)])
|
||
|
|
async def test_pyramid_errors_preserve_access_boundary(settings, status, code, expected_calls):
|
||
|
|
calls = []
|
||
|
|
|
||
|
|
def upstream(request):
|
||
|
|
calls.append(request)
|
||
|
|
return httpx.Response(status, json={"detail": "private-upstream-body"})
|
||
|
|
|
||
|
|
client = WqClient(settings, transport=httpx.MockTransport(upstream))
|
||
|
|
client.credentials, client.authenticated = ("test@example.com", "test-only"), True
|
||
|
|
try:
|
||
|
|
with pytest.raises(WqError) as error:
|
||
|
|
await client.get_pyramid_alphas()
|
||
|
|
assert error.value.code == code
|
||
|
|
assert "private-upstream-body" not in str(error.value)
|
||
|
|
assert len(calls) == expected_calls
|
||
|
|
assert all(not request.url.query for request in calls)
|
||
|
|
finally:
|
||
|
|
await client.close()
|
||
|
|
|
||
|
|
|
||
|
|
def test_pyramid_normalization_preserves_zero_unknown_and_allowlist():
|
||
|
|
rows = pyramid_rows({"pyramids": [pyramid(alphaCount=0, token="private"), pyramid()]}, "alphaCount")
|
||
|
|
assert rows[0].value == 0 and rows[1].value is None
|
||
|
|
assert "private" not in str(rows)
|
||
|
|
assert pyramid_rows({"pyramids": []}, "multiplier") == []
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize("data", [
|
||
|
|
{}, {"pyramids": {}}, {"pyramids": [None]},
|
||
|
|
{"pyramids": [pyramid(alphaCount="3")]},
|
||
|
|
{"pyramids": [pyramid(alphaCount=True)]},
|
||
|
|
{"pyramids": [pyramid(alphaCount=-1)]},
|
||
|
|
{"pyramids": [pyramid(alphaCount=2.5)]},
|
||
|
|
{"pyramids": [pyramid(alphaCount=float("nan"))]},
|
||
|
|
{"pyramids": [pyramid(category=None)]},
|
||
|
|
])
|
||
|
|
def test_pyramid_unknown_shapes_are_not_empty_success(data):
|
||
|
|
with pytest.raises(WqError, match="格式无法识别"):
|
||
|
|
pyramid_rows(data, "alphaCount")
|
||
|
|
|
||
|
|
|
||
|
|
async def test_dashboard_auth_connection_dates_and_independent_errors(app, client, logged_in, monkeypatch):
|
||
|
|
calls = []
|
||
|
|
|
||
|
|
async def read_alphas(start_date=None, end_date=None):
|
||
|
|
calls.append((start_date, end_date))
|
||
|
|
return {"pyramids": [pyramid(alphaCount=7)], "token": "private"}
|
||
|
|
|
||
|
|
async def read_multipliers():
|
||
|
|
raise WqError("无权访问该平台资源", "access_denied")
|
||
|
|
|
||
|
|
monkeypatch.setattr(app.state.runner.client, "get_pyramid_alphas", read_alphas)
|
||
|
|
monkeypatch.setattr(app.state.runner.client, "get_pyramid_multipliers", read_multipliers)
|
||
|
|
prefix = "/api/v1/dashboard"
|
||
|
|
assert (await logged_in.get(f"{prefix}/pyramid-alphas")).status_code == 409
|
||
|
|
assert calls == []
|
||
|
|
async with app.state.sessions.begin() as db:
|
||
|
|
account = await db.get(Account, 1)
|
||
|
|
account.connection_status, account.wq_user_id = "connected", "TEST_USER"
|
||
|
|
for query in ("start_date=bad", "start_date=2026-08-02&end_date=2026-08-01"):
|
||
|
|
assert (await logged_in.get(f"{prefix}/pyramid-alphas?{query}")).status_code == 422
|
||
|
|
assert calls == []
|
||
|
|
response = await logged_in.get(f"{prefix}/pyramid-alphas?start_date=2026-07-01&end_date=2026-07-31")
|
||
|
|
assert response.status_code == 200
|
||
|
|
assert calls == [("2026-07-01", "2026-07-31")]
|
||
|
|
result = response.json()
|
||
|
|
assert result["items"][0] == {
|
||
|
|
"region": "USA", "delay": 1, "category_id": "analyst", "category_name": "Analyst", "value": 7,
|
||
|
|
}
|
||
|
|
assert result["start_date"] == "2026-07-01" and result["end_date"] == "2026-07-31"
|
||
|
|
assert datetime.fromisoformat(result["fetched_at"]).tzinfo is not None
|
||
|
|
assert "private" not in response.text
|
||
|
|
assert (await logged_in.get(f"{prefix}/pyramid-multipliers")).status_code == 502
|
||
|
|
assert (await logged_in.get("/api/v1/auth/me")).status_code == 200
|
||
|
|
await logged_in.get(f"{prefix}/pyramid-alphas")
|
||
|
|
assert calls[-1] == (None, None)
|
||
|
|
await logged_in.get(f"{prefix}/pyramid-alphas?end_date=2026-07-31")
|
||
|
|
assert calls[-1] == (None, "2026-07-31")
|
||
|
|
client.cookies.clear()
|
||
|
|
for endpoint in ("pyramid-alphas", "pyramid-multipliers"):
|
||
|
|
assert (await client.get(f"{prefix}/{endpoint}")).status_code == 401
|