334 lines
13 KiB
Python
334 lines
13 KiB
Python
import io
|
|
from copy import deepcopy
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import pytest
|
|
from fastapi import FastAPI, HTTPException
|
|
from httpx import ASGITransport, AsyncClient
|
|
from PIL import Image
|
|
from pydantic import ValidationError
|
|
|
|
from app.api.v1.card_images import router
|
|
from app.core.security import get_current_user
|
|
from app.db.session import get_db
|
|
from app.schemas.card_images import CardImageAsset, CardImageConfiguration, CardImageRule
|
|
from app.services.card_image_configuration import (
|
|
effective_envelope,
|
|
publish_configuration,
|
|
resolve_image,
|
|
)
|
|
from app.services.card_image_defaults import bundled_configuration
|
|
from app.services import card_image_files
|
|
|
|
|
|
def configuration():
|
|
assets = [
|
|
CardImageAsset(id=key, title=key, url=f"/earth/assets/cards/{key}.jpg")
|
|
for key in ["exact", "model", "group", "category"]
|
|
]
|
|
rules = [
|
|
CardImageRule(id=key, entity_type="satellite", scope=scope, value=value, asset_id=key)
|
|
for key, scope, value in [
|
|
("exact", "object", "123"),
|
|
("model", "model", "m1"),
|
|
("group", "group", "starlink"),
|
|
("category", "category", "satellite"),
|
|
]
|
|
]
|
|
return CardImageConfiguration(assets=assets, rules=rules)
|
|
|
|
|
|
def test_precedence_disabled_fallback_and_explicit_no_image():
|
|
config = configuration()
|
|
context = dict(
|
|
entity_type="satellite", entity_id="123", model="M1", group="starlink", category="satellite"
|
|
)
|
|
for expected in ["exact", "model", "group", "category"]:
|
|
assert resolve_image(config, context)["image"]["id"] == expected
|
|
next(asset for asset in config.assets if asset.id == expected).enabled = False
|
|
assert resolve_image(config, context)["image"] is None
|
|
config = configuration()
|
|
config.rules[0].asset_id = None
|
|
config.rules[0].suppress = True
|
|
result = resolve_image(config, context)
|
|
assert result["suppressed"] and result["image"] is None
|
|
|
|
|
|
def test_bundled_series_images_retain_truthful_source_metadata():
|
|
config, _ = bundled_configuration()
|
|
result = resolve_image(config, dict(entity_type="satellite", entity_id="123", group="starlink"))
|
|
assert result["image"]["id"] == "starlink-solar-array"
|
|
pending = next(asset for asset in config.assets if asset.id == "qianfan-animation-still")
|
|
assert pending.rights_status == "permission_pending"
|
|
assert (
|
|
resolve_image(config, dict(entity_type="satellite", group="qianfan"))["image"]["id"]
|
|
== pending.id
|
|
)
|
|
assert pending.enabled
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"url",
|
|
[
|
|
"javascript:alert(1)",
|
|
"//evil.example/image.jpg",
|
|
"/earth/assets/cards/../secret",
|
|
"https://user:pass@example.org/a.jpg",
|
|
],
|
|
)
|
|
def test_unsafe_urls_rejected(url):
|
|
with pytest.raises(ValidationError):
|
|
CardImageAsset(id="test", title="test", url=url)
|
|
|
|
|
|
def test_duplicate_targets_and_dangling_assets_rejected():
|
|
data = configuration().model_dump()
|
|
duplicate = {**data["rules"][0], "id": "another"}
|
|
data["rules"].append(duplicate)
|
|
with pytest.raises(ValidationError):
|
|
CardImageConfiguration.model_validate(data)
|
|
data = configuration().model_dump()
|
|
data["assets"] = []
|
|
with pytest.raises(ValidationError):
|
|
CardImageConfiguration.model_validate(data)
|
|
|
|
|
|
def test_new_defaults_do_not_undo_saved_removals_or_manual_edits():
|
|
defaults, _ = bundled_configuration()
|
|
payload = {
|
|
"revision": "custom",
|
|
"config": {"assets": [], "rules": []},
|
|
"known_assets": [asset.id for asset in defaults.assets],
|
|
"known_rules": [rule.id for rule in defaults.rules],
|
|
}
|
|
assert effective_envelope(payload)["config"] == {"assets": [], "rules": []}
|
|
payload["known_assets"] = []
|
|
assert len(effective_envelope(payload)["config"]["assets"]) == len(defaults.assets)
|
|
|
|
|
|
@pytest.mark.parametrize("format", ["JPEG", "PNG", "WEBP"])
|
|
def test_upload_verifies_raster_and_creates_reusable_variants(tmp_path, monkeypatch, format):
|
|
monkeypatch.setattr(card_image_files, "ASSET_DIR", tmp_path)
|
|
output = io.BytesIO()
|
|
Image.new("RGB", (1600, 900), "blue").save(output, format)
|
|
asset = card_image_files.store_image(output.getvalue(), "Facility")
|
|
assert (asset.width, asset.height) == (1600, 900)
|
|
assert len(list(tmp_path.iterdir())) == 3
|
|
for size, url in asset.variants.items():
|
|
with Image.open(tmp_path / url.rsplit("/", 1)[1]) as image:
|
|
assert max(image.size) == int(size)
|
|
assert card_image_files.store_image(output.getvalue(), "Again").id == asset.id
|
|
with pytest.raises(HTTPException):
|
|
card_image_files.store_image(b"<svg></svg>", "bad")
|
|
with pytest.raises(HTTPException):
|
|
card_image_files.uploaded_path("../private")
|
|
|
|
|
|
def fake_db(payload):
|
|
db = AsyncMock()
|
|
db.add = MagicMock()
|
|
record = SimpleNamespace(payload=payload)
|
|
result = MagicMock()
|
|
result.scalar_one.return_value = record
|
|
result.scalar_one_or_none.return_value = record
|
|
db.execute.return_value = result
|
|
return db, record
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_publish_revision_and_audit():
|
|
defaults, _ = bundled_configuration()
|
|
payload = {
|
|
"revision": "default",
|
|
"config": defaults.model_dump(mode="json"),
|
|
"known_assets": [],
|
|
"known_rules": [],
|
|
}
|
|
db, record = fake_db(payload)
|
|
revision = effective_envelope(payload)["revision"]
|
|
result = await publish_configuration(
|
|
db, revision, defaults, SimpleNamespace(id=1, username="admin")
|
|
)
|
|
assert result["revision"] != revision
|
|
assert db.add.call_args.args[0].action == "card_images.update"
|
|
before = deepcopy(record.payload)
|
|
with pytest.raises(HTTPException) as error:
|
|
await publish_configuration(db, revision, defaults, SimpleNamespace(id=1, username="admin"))
|
|
assert error.value.status_code == 409 and record.payload == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_configuration_requires_admin_and_validates_http_payload():
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
defaults, _ = bundled_configuration()
|
|
db, _ = fake_db(
|
|
{
|
|
"revision": "default",
|
|
"config": defaults.model_dump(mode="json"),
|
|
"known_assets": [],
|
|
"known_rules": [],
|
|
}
|
|
)
|
|
app.dependency_overrides[get_db] = lambda: db
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
assert (await client.get("/configuration")).status_code == 401
|
|
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(role="viewer")
|
|
assert (await client.get("/configuration")).status_code == 403
|
|
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
|
|
role="admin", id=1, username="admin"
|
|
)
|
|
assert (await client.get("/configuration")).status_code == 200
|
|
assert (
|
|
await client.put("/configuration", json={"revision": "x", "config": {"rules": [{}]}})
|
|
).status_code == 422
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_multipart_upload_and_public_file_delivery(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(card_image_files, "ASSET_DIR", tmp_path)
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
|
|
role="admin", id=1, username="admin"
|
|
)
|
|
buffer = io.BytesIO()
|
|
Image.new("RGB", (800, 500), "blue").save(buffer, "JPEG")
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
response = await client.post(
|
|
"/upload", files={"file": ("facility.jpg", buffer.getvalue(), "image/jpeg")}
|
|
)
|
|
assert response.status_code == 200
|
|
asset = response.json()
|
|
filename = asset["variants"]["640"].rsplit("/", 1)[1]
|
|
image = await client.get(f"/files/{filename}")
|
|
assert image.status_code == 200 and image.headers["content-type"] == "image/webp"
|
|
assert "immutable" in image.headers["cache-control"]
|
|
assert (
|
|
await client.post("/upload", files={"file": ("bad.jpg", b"not an image", "image/jpeg")})
|
|
).status_code == 422
|
|
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(role="viewer")
|
|
assert (
|
|
await client.post(
|
|
"/upload", files={"file": ("facility.jpg", buffer.getvalue(), "image/jpeg")}
|
|
)
|
|
).status_code == 403
|
|
|
|
|
|
def test_all_object_types_have_a_default_without_overriding_exact_suppression():
|
|
from typing import get_args
|
|
from app.schemas.card_images import EntityType
|
|
|
|
config, _ = bundled_configuration()
|
|
for entity_type in get_args(EntityType):
|
|
result = resolve_image(config, dict(entity_type=entity_type, category="unlisted"))
|
|
assert result["image"] and result["match"]["value"] == "*"
|
|
config = config.model_copy(deep=True)
|
|
config.rules.append(
|
|
CardImageRule(id="off", entity_type="satellite", scope="object", value="123", suppress=True)
|
|
)
|
|
assert resolve_image(config, dict(entity_type="satellite", entity_id="123"))["suppressed"]
|
|
|
|
|
|
def test_upgrade_replaces_old_bundled_source_but_preserves_custom_assets():
|
|
from app.services.card_image_defaults import previous_bundled_assets
|
|
|
|
old = previous_bundled_assets()["starlink-solar-array"][0]
|
|
payload = {
|
|
"revision": "old",
|
|
"config": {"assets": [old.model_dump()], "rules": []},
|
|
"known_assets": [old.id],
|
|
"known_rules": [],
|
|
}
|
|
|
|
def starlink():
|
|
return next(a for a in effective_envelope(payload)["config"]["assets"] if a["id"] == old.id)
|
|
|
|
assert starlink()["url"].endswith("starlink-orbit.webp")
|
|
payload["config"]["assets"][0]["focus_x"] = 20
|
|
assert starlink()["focus_x"] == 20
|
|
assert starlink()["url"].endswith("starlink-orbit.webp")
|
|
payload["config"]["assets"][0]["enabled"] = False
|
|
assert starlink()["enabled"] is False
|
|
payload["config"]["assets"][0]["url"] = "https://example.org/custom.jpg"
|
|
assert starlink()["url"] == "https://example.org/custom.jpg"
|
|
|
|
|
|
def test_compute_categories_and_bgp_get_separate_user_images():
|
|
config, _ = bundled_configuration()
|
|
for kind, filename in [
|
|
("supercomputer", "supercomputer.png"),
|
|
("gpu_cluster", "gpu-cluster.jpg"),
|
|
("data_center", "data-center.png"),
|
|
("cloud_center", "cloud-center.png"),
|
|
("edge_node", "edge-node.png"),
|
|
]:
|
|
result = resolve_image(config, dict(entity_type="compute_center", category=kind))
|
|
assert result["image"]["url"].endswith(filename)
|
|
for kind in ("bgp", "bgp_collector"):
|
|
result = resolve_image(config, dict(entity_type=kind, category=kind))
|
|
assert result["image"]["url"].endswith(
|
|
"bgp-event.jpg" if kind == "bgp" else "bgp-collector.png"
|
|
)
|
|
|
|
|
|
def test_saved_collector_default_migrates_without_changing_user_bindings():
|
|
from app.services.card_image_defaults import previous_bundled_rules, previous_bundled_assets
|
|
|
|
old_rule = previous_bundled_rules()["builtin-network-switches-default-1"]
|
|
old_asset = previous_bundled_assets()["network-switches"][0]
|
|
payload = {
|
|
"revision": "old",
|
|
"config": {"assets": [old_asset.model_dump()], "rules": [old_rule.model_dump()]},
|
|
"known_assets": [old_asset.id],
|
|
"known_rules": [old_rule.id],
|
|
}
|
|
result = CardImageConfiguration.model_validate(effective_envelope(payload)["config"])
|
|
assert resolve_image(result, dict(entity_type="bgp_collector", category="bgp_collector"))[
|
|
"image"
|
|
]["url"].endswith("bgp-collector.png")
|
|
payload["config"]["rules"][0]["enabled"] = False
|
|
result = effective_envelope(payload)["config"]
|
|
assert not next(rule for rule in result["rules"] if rule["id"] == old_rule.id)["enabled"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_compute_lookup_filters_indexed_identity_and_keeps_actual_category():
|
|
from app.services.card_image_targets import get_target
|
|
from sqlalchemy.dialects import postgresql
|
|
|
|
db = AsyncMock()
|
|
result = MagicMock()
|
|
result.mappings.return_value.first.return_value = {
|
|
"entity_id": "epoch_ai_gpu:site",
|
|
"name": "Site",
|
|
"category": "cloud_center",
|
|
"group": "Operator",
|
|
"model": "Model",
|
|
}
|
|
db.execute.return_value = result
|
|
context = await get_target(db, "compute_center", "epoch_ai_gpu:site")
|
|
query = db.execute.call_args.args[0]
|
|
sql = str(query.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}))
|
|
assert "collected_data.source = 'epoch_ai_gpu'" in sql
|
|
assert "collected_data.source_id = 'site'" in sql
|
|
assert context["category"] == "cloud_center" and context["model"] == "Model"
|
|
|
|
|
|
def test_old_gpu_preview_urls_are_replaced_with_latest_variants():
|
|
from app.services.card_image_defaults import previous_bundled_assets
|
|
|
|
old = previous_bundled_assets()["compute-gpu-cluster"][0]
|
|
payload = {
|
|
"revision": "old",
|
|
"config": {"assets": [old.model_dump()], "rules": []},
|
|
"known_assets": [old.id],
|
|
"known_rules": [],
|
|
}
|
|
result = effective_envelope(payload)["config"]
|
|
upgraded = next(a for a in result["assets"] if a["id"] == old.id)
|
|
latest = next(a for a in bundled_configuration()[0].assets if a.id == old.id)
|
|
assert upgraded["variants"] == latest.variants
|
|
assert upgraded["url"] == latest.url
|