2026-09-09 18:20:08 +08:00
|
|
|
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
|
2026-09-12 00:04:57 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def activity_data(rows, properties=None):
|
|
|
|
|
return {"records": {"schema": {"properties": properties or ["date", "value"]}, "records": rows}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_activity_calendar_preserves_missing_zero_and_column_order():
|
|
|
|
|
from app.dashboard import activity_snapshot
|
|
|
|
|
|
|
|
|
|
at = datetime.fromisoformat("2026-09-11T02:00:00+00:00")
|
|
|
|
|
data = activity_data([
|
|
|
|
|
[3, "2026-09-10", "private"], [0, "2026-09-09", "private"],
|
|
|
|
|
[99, "2026-09-11", "future"], [15, "2025-01-01", "old"],
|
|
|
|
|
], [{"name": "value"}, {"name": "date"}, {"name": "secret"}])
|
|
|
|
|
result = activity_snapshot(data, 14, at)
|
|
|
|
|
assert result.today.isoformat() == "2026-09-10"
|
|
|
|
|
assert len(result.items) == 14 and result.items[0].date.isoformat() == "2026-08-28"
|
|
|
|
|
assert [day.count for day in result.items[-3:]] == [None, 0, 3]
|
|
|
|
|
assert "private" not in result.model_dump_json()
|
|
|
|
|
assert result.timezone == "America/New_York"
|
|
|
|
|
assert len(activity_snapshot(data, 182, at).items) == 182
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("timestamp,today", [
|
|
|
|
|
("2026-03-08T04:59:59+00:00", "2026-03-07"),
|
|
|
|
|
("2026-03-08T05:00:00+00:00", "2026-03-08"),
|
|
|
|
|
("2026-03-09T04:00:00+00:00", "2026-03-09"),
|
|
|
|
|
("2026-11-01T04:00:00+00:00", "2026-11-01"),
|
|
|
|
|
("2026-11-02T04:59:59+00:00", "2026-11-01"),
|
|
|
|
|
("2026-11-02T05:00:00+00:00", "2026-11-02"),
|
|
|
|
|
("2027-01-01T04:00:00+00:00", "2026-12-31"),
|
|
|
|
|
])
|
|
|
|
|
def test_activity_uses_eastern_calendar_across_dst_and_year(timestamp, today):
|
|
|
|
|
from app.dashboard import activity_snapshot
|
|
|
|
|
|
|
|
|
|
result = activity_snapshot(activity_data([]), 14, datetime.fromisoformat(timestamp))
|
|
|
|
|
assert result.today.isoformat() == today
|
|
|
|
|
assert all(day.count is None for day in result.items)
|
|
|
|
|
assert len({day.date for day in result.items}) == 14
|
|
|
|
|
assert (result.items[-1].date - result.items[0].date).days == 13
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("data", [
|
|
|
|
|
{}, {"records": None}, activity_data([None]), activity_data([["2026-09-10"]]),
|
|
|
|
|
activity_data([["invalid", 1]]), activity_data([["20260910", 1]]),
|
|
|
|
|
activity_data([["2026-09-10", True]]), activity_data([["2026-09-10", -1]]),
|
|
|
|
|
activity_data([["2026-09-10", 1.5]]), activity_data([["2026-09-10", "3"]]),
|
|
|
|
|
activity_data([["2026-09-10", 1], ["2026-09-10", 2]]),
|
|
|
|
|
activity_data([], ["date", "date", "value"]), activity_data([], ["date"]),
|
|
|
|
|
])
|
|
|
|
|
def test_activity_rejects_malformed_or_ambiguous_counts(data):
|
|
|
|
|
from app.dashboard import activity_snapshot
|
|
|
|
|
|
|
|
|
|
with pytest.raises(WqError, match="格式无法识别"):
|
|
|
|
|
activity_snapshot(data, 14, datetime.fromisoformat("2026-09-11T12:00:00+00:00"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def test_activity_endpoint_auth_connection_and_independent_failures(app, client, logged_in, monkeypatch):
|
|
|
|
|
calls = []
|
|
|
|
|
|
|
|
|
|
async def read(path):
|
|
|
|
|
calls.append(path)
|
|
|
|
|
if path.endswith("simulations"):
|
|
|
|
|
raise WqError("无权访问该平台资源", "access_denied")
|
|
|
|
|
return activity_data([])
|
|
|
|
|
|
|
|
|
|
monkeypatch.setattr(app.state.runner.client, "get", read)
|
|
|
|
|
prefix = "/api/v1/dashboard/activity"
|
|
|
|
|
assert (await logged_in.get(f"{prefix}/submissions")).status_code == 409
|
|
|
|
|
assert not 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"
|
|
|
|
|
assert (await logged_in.get(f"{prefix}/arbitrary")).status_code == 422
|
|
|
|
|
assert not calls
|
|
|
|
|
response = await logged_in.get(f"{prefix}/submissions")
|
|
|
|
|
assert response.status_code == 200 and len(response.json()["items"]) == 182
|
|
|
|
|
assert all(day["count"] is None for day in response.json()["items"])
|
|
|
|
|
assert (await logged_in.get(f"{prefix}/simulations")).status_code == 502
|
|
|
|
|
assert calls == ["/users/self/activities/submissions", "/users/self/activities/simulations"]
|
|
|
|
|
assert (await logged_in.get("/api/v1/auth/me")).status_code == 200
|
|
|
|
|
|
|
|
|
|
async def waiting(path):
|
|
|
|
|
raise WqError("需要人工验证", "verification_required")
|
|
|
|
|
|
|
|
|
|
monkeypatch.setattr(app.state.runner.client, "get", waiting)
|
|
|
|
|
assert (await logged_in.get(f"{prefix}/submissions")).status_code == 409
|
|
|
|
|
client.cookies.clear()
|
|
|
|
|
assert (await client.get(f"{prefix}/submissions")).status_code == 401
|
|
|
|
|
assert (await client.get(f"{prefix}/simulations")).status_code == 401
|