Three-month batch sync from internal repo (~80 commits) covering Tracks F.5a, F.7e, F.8, F.17, F.18, F.X. WordPress media pipeline - Pillow-based optimization, AI image generation (OpenAI / Stability / Replicate / Google Nano Banana / OpenRouter), chunked + resumable uploads, bulk delete/reassign, idempotent retries. Capability discovery (F.7e) - Per-site credential probe + adapters for WordPress / WooCommerce / Gitea, tier-fit unions granted ∪ roles, capability badge UI with HTMX partial re-check, install hint in every companion-unreachable error. Companion plugin overhaul - Renamed wordpress-plugin/airano-mcp-seo-bridge → wordpress-plugin/airano-mcp-bridge. - Eight new endpoints: /capabilities, /bulk-meta, /export, /cache-purge, /transient-flush, /site-health, /audit-hook, /upload-and-attach. - wp.org Plugin Check pass: i18n, WP_Filesystem, scheme allowlist on audit-hook URL. Other - Gitea ergonomics (F.17): batch files, tree, search, compare, releases, fork. - Opportunistic bcrypt upgrade for legacy SHA-256 admin keys (F.8). - n8n refactor: structured errors, capability probe, missing tools backfilled. - Idempotency-Key dedup for AI media upload retries; WP client fast-fails on unreachable sites. Docs - README + CLAUDE.md drop the fixed "633 tools" claim. The total grows with each release; per-plugin approximations + dashboard-surfaced counts replace it. - Tools/Tests badges removed in favour of "Plugins: 10". Deployment - PyPI mirror chain, optional BUILD_HTTP_PROXY, Alpine→Yandex apk mirror, Debian-slim Plan-B Dockerfile, mirror.gcr.io variant. CI - Black + Ruff clean on Python 3.12; pytest tests/ green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
158 lines
5.5 KiB
Python
158 lines
5.5 KiB
Python
"""F.X.fix #11 — OpenRouter pricing table for cost_usd attribution."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
|
|
from plugins.ai_image.providers.base import GenerationRequest, ProviderError
|
|
from plugins.ai_image.providers.openrouter import (
|
|
_MODEL_PRICING,
|
|
OpenRouterProvider,
|
|
_cost_for,
|
|
_pricing_table,
|
|
)
|
|
|
|
_PNG_1x1 = base64.b64decode(
|
|
b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
|
|
)
|
|
|
|
|
|
def _fake_resp(*, status, json_data=None, text_data="", raw=None, headers=None):
|
|
resp = AsyncMock()
|
|
resp.status = status
|
|
resp.text = AsyncMock(return_value=text_data or "")
|
|
if json_data is not None:
|
|
resp.json = AsyncMock(return_value=json_data)
|
|
if raw is not None:
|
|
resp.read = AsyncMock(return_value=raw)
|
|
resp.headers = headers or {}
|
|
return resp
|
|
|
|
|
|
def _mock_session(responses):
|
|
iterator = iter(responses)
|
|
|
|
def _request(*_a, **_kw):
|
|
resp = next(iterator)
|
|
return AsyncMock(
|
|
__aenter__=AsyncMock(return_value=resp),
|
|
__aexit__=AsyncMock(return_value=False),
|
|
)
|
|
|
|
sess = AsyncMock()
|
|
sess.post = _request
|
|
sess.get = _request
|
|
return sess
|
|
|
|
|
|
class TestPricingTable:
|
|
def test_known_model_maps_to_non_null_cost(self):
|
|
assert _cost_for("google/gemini-2.5-flash-image") is not None
|
|
assert _cost_for("google/gemini-2.5-flash-image") > 0
|
|
|
|
def test_unknown_model_returns_none(self, caplog):
|
|
assert _cost_for("nonexistent/model-xyz") is None
|
|
|
|
def test_gemini_preview_still_priced(self):
|
|
# Preview alias is deprecated but still has a price entry so if
|
|
# an admin call bypasses the generate-time guard the cost column
|
|
# is still usable for audit.
|
|
assert _cost_for("google/gemini-2.5-flash-image-preview") is not None
|
|
|
|
def test_pricing_table_contains_expected_providers(self):
|
|
ids = set(_MODEL_PRICING.keys())
|
|
assert any(m.startswith("google/gemini-") for m in ids)
|
|
assert any(m.startswith("openai/dall-e") for m in ids)
|
|
assert any(m.startswith("black-forest-labs/flux") for m in ids)
|
|
|
|
def test_env_override_merges_and_wins(self, monkeypatch):
|
|
monkeypatch.setenv(
|
|
"OPENROUTER_PRICING_OVERRIDE",
|
|
json.dumps({"google/gemini-2.5-flash-image": 0.001, "custom/model": 0.5}),
|
|
)
|
|
table = _pricing_table()
|
|
assert table["google/gemini-2.5-flash-image"] == 0.001
|
|
assert table["custom/model"] == 0.5
|
|
# Untouched entries stay from the hard-coded table.
|
|
assert "openai/dall-e-3" in table
|
|
|
|
def test_env_override_bad_json_is_ignored(self, monkeypatch):
|
|
monkeypatch.setenv("OPENROUTER_PRICING_OVERRIDE", "not-json{")
|
|
# Falls back to the default table, no exception.
|
|
assert (
|
|
_pricing_table()["google/gemini-2.5-flash-image"]
|
|
== _MODEL_PRICING["google/gemini-2.5-flash-image"]
|
|
)
|
|
|
|
|
|
class TestGenerateAttributesCost:
|
|
@pytest.mark.asyncio
|
|
async def test_cost_usd_populated_for_known_model(self):
|
|
provider = OpenRouterProvider()
|
|
b64 = base64.b64encode(_PNG_1x1).decode()
|
|
ok = _fake_resp(
|
|
status=200,
|
|
json_data={
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"images": [{"image_url": {"url": f"data:image/png;base64,{b64}"}}]
|
|
}
|
|
}
|
|
]
|
|
},
|
|
)
|
|
sess = _mock_session([ok])
|
|
with patch("plugins.ai_image.providers.openrouter.aiohttp.ClientSession") as cls:
|
|
cls.return_value = AsyncMock(
|
|
__aenter__=AsyncMock(return_value=sess),
|
|
__aexit__=AsyncMock(return_value=False),
|
|
)
|
|
result = await provider.generate("k", GenerationRequest(prompt="x"))
|
|
assert result.cost_usd == _MODEL_PRICING["google/gemini-2.5-flash-image"]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cost_usd_null_for_unknown_model(self):
|
|
provider = OpenRouterProvider()
|
|
b64 = base64.b64encode(_PNG_1x1).decode()
|
|
ok = _fake_resp(
|
|
status=200,
|
|
json_data={
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"images": [{"image_url": {"url": f"data:image/png;base64,{b64}"}}]
|
|
}
|
|
}
|
|
]
|
|
},
|
|
)
|
|
sess = _mock_session([ok])
|
|
with patch("plugins.ai_image.providers.openrouter.aiohttp.ClientSession") as cls:
|
|
cls.return_value = AsyncMock(
|
|
__aenter__=AsyncMock(return_value=sess),
|
|
__aexit__=AsyncMock(return_value=False),
|
|
)
|
|
result = await provider.generate(
|
|
"k", GenerationRequest(prompt="x", model="weird/unreleased-model")
|
|
)
|
|
assert result.cost_usd is None
|
|
|
|
|
|
class TestDeprecatedModelGuard:
|
|
@pytest.mark.asyncio
|
|
async def test_preview_model_raises_model_deprecated(self):
|
|
provider = OpenRouterProvider()
|
|
with pytest.raises(ProviderError) as e:
|
|
await provider.generate(
|
|
"k",
|
|
GenerationRequest(prompt="x", model="google/gemini-2.5-flash-image-preview"),
|
|
)
|
|
assert e.value.code == "PROVIDER_MODEL_DEPRECATED"
|
|
assert "google/gemini-2.5-flash-image" in str(e.value.message)
|
|
assert e.value.details.get("replacement_model") == "google/gemini-2.5-flash-image"
|