mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 16:36:28 +08:00
fix(channels): parse extension identifiers without global caching (#7640)
This commit is contained in:
@@ -622,6 +622,47 @@ class NotificationChannel(Enum):
|
||||
# QQ 消息渠道
|
||||
QQ = "QQ"
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> Optional["NotificationChannel"]:
|
||||
"""
|
||||
解析带命名空间的扩展值而不缓存;格式合法不代表平台注册或入口可信。
|
||||
"""
|
||||
if not isinstance(value, str) or re.fullmatch(r"platform:[a-z][a-z0-9._-]{0,54}", value) is None:
|
||||
return None
|
||||
member = object.__new__(cls)
|
||||
member._name_ = value
|
||||
member._value_ = value
|
||||
return member
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
"""
|
||||
同类枚举按传输值比较,保证无缓存扩展在入站核对和序列化后仍相等。
|
||||
"""
|
||||
if isinstance(other, NotificationChannel):
|
||||
return self.value == other.value
|
||||
return NotImplemented
|
||||
|
||||
def __hash__(self) -> int:
|
||||
"""
|
||||
保持内置枚举的名称哈希,并让同值扩展可稳定用于集合和字典。
|
||||
"""
|
||||
return hash(self._name_)
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_json_schema__(
|
||||
cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler,
|
||||
) -> dict[str, object]:
|
||||
"""
|
||||
保留全部内置值并公开扩展格式,枚举成员不能被误当作授权白名单。
|
||||
"""
|
||||
schema: dict[str, object] = handler(core_schema)
|
||||
values = schema.pop("enum", [member.value for member in cls])
|
||||
schema["anyOf"] = [
|
||||
{"type": "string", "enum": values},
|
||||
{"type": "string", "pattern": r"^platform:[a-z][a-z0-9._-]{0,54}$"},
|
||||
]
|
||||
return schema
|
||||
|
||||
|
||||
class NotificationAction(str, Enum):
|
||||
"""
|
||||
|
||||
109
tests/contracts/test_notification_transport_identifiers.py
Normal file
109
tests/contracts/test_notification_transport_identifiers.py
Normal file
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
扩展传输标识的无状态解析、持久化边界和公开序列化回归。
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from pydantic import TypeAdapter
|
||||
|
||||
from app.schemas.types import NotificationChannel
|
||||
|
||||
|
||||
def test_uncached_transport_preserves_enum_equality_hashing_and_builtin_identity():
|
||||
"""
|
||||
无缓存扩展仍可比较和充当键,复制与序列化不改变值;内置成员继续保持单例。
|
||||
"""
|
||||
import copy
|
||||
import pickle
|
||||
|
||||
from pydantic import TypeAdapter
|
||||
|
||||
first = NotificationChannel("platform:uncached-equality")
|
||||
second = NotificationChannel("platform:uncached-equality")
|
||||
different = NotificationChannel("platform:uncached-other")
|
||||
adapter = TypeAdapter(NotificationChannel)
|
||||
assert first == second and first != different
|
||||
assert hash(first) == hash(second)
|
||||
assert {first: "owner"}[second] == "owner"
|
||||
assert len({first, second, different}) == 2
|
||||
assert first != first.value and first != object()
|
||||
assert first not in {NotificationChannel.Web, NotificationChannel.WebAgent}
|
||||
assert copy.copy(first) == first
|
||||
assert copy.deepcopy(first) == first
|
||||
assert pickle.loads(pickle.dumps(first)) == first
|
||||
assert adapter.validate_json(adapter.dump_json(first)) == first
|
||||
for member in NotificationChannel:
|
||||
assert NotificationChannel(member.value) is member
|
||||
assert NotificationChannel[member.name] is member
|
||||
assert adapter.validate_json(adapter.dump_json(member)) is member
|
||||
assert hash(member) == hash(member.name)
|
||||
assert member != member.value
|
||||
|
||||
|
||||
def test_public_transport_schema_preserves_builtin_values_and_namespaced_extensions():
|
||||
"""
|
||||
公开接口的 Schema 同时发布内置值和扩展格式,编码往返不能丢失独立平台身份。
|
||||
"""
|
||||
import re
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.schemas.message import IncomingMessage
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
@app.post("/message", response_model=IncomingMessage)
|
||||
def echo_message(message: IncomingMessage) -> IncomingMessage:
|
||||
"""
|
||||
保留真实公开消息 DTO 的编解码,不接入授权或外部传输。
|
||||
"""
|
||||
return message
|
||||
|
||||
schema = app.openapi()["components"]["schemas"]["NotificationChannel"]
|
||||
builtins, extension = schema["anyOf"]
|
||||
assert set(builtins["enum"]) == {member.value for member in NotificationChannel}
|
||||
assert "enum" not in schema
|
||||
pattern = extension["pattern"]
|
||||
maximum = "platform:" + "a" * 55
|
||||
assert len(maximum) == 64 and re.fullmatch(pattern, maximum)
|
||||
assert not re.fullmatch(pattern, maximum + "a")
|
||||
assert not re.fullmatch(pattern, "platform:Bad")
|
||||
with TestClient(app) as client:
|
||||
for channel in ("Telegram", "platform:independent-fixture", maximum):
|
||||
response = client.post("/message", json={"channel": channel, "userid": "p-alice"})
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json()["channel"] == channel
|
||||
assert client.post("/message", json={"channel": "unknown", "userid": "p-alice"}).status_code == 422
|
||||
assert all(member.value != maximum for member in NotificationChannel)
|
||||
with pytest.raises(ValueError):
|
||||
NotificationChannel(123)
|
||||
|
||||
|
||||
def test_unknown_transport_batch_keeps_enum_registry_bounded():
|
||||
"""
|
||||
解析和序列化大量未注册标识不能修改进程级枚举成员表。
|
||||
"""
|
||||
values_before = dict(NotificationChannel._value2member_map_)
|
||||
members_before = dict(NotificationChannel.__members__)
|
||||
names_before = tuple(NotificationChannel._member_names_)
|
||||
adapter = TypeAdapter(NotificationChannel)
|
||||
for index in range(4096):
|
||||
identifier = f"platform:unregistered-batch-{index}"
|
||||
channel = NotificationChannel(identifier)
|
||||
decoded = adapter.validate_json(json.dumps(identifier))
|
||||
assert channel == decoded
|
||||
assert adapter.dump_json(decoded) == json.dumps(identifier).encode()
|
||||
assert NotificationChannel._value2member_map_ == values_before
|
||||
assert dict(NotificationChannel.__members__) == members_before
|
||||
assert tuple(NotificationChannel._member_names_) == names_before
|
||||
|
||||
|
||||
@pytest.mark.parametrize("identifier", ["platform:", "platform:Bad", "platform:" + "a" * 56, "platform:with space"])
|
||||
def test_extension_transport_identifiers_fit_persistent_contract(identifier):
|
||||
"""
|
||||
扩展传输格式与现有 64 字符持久化限制一致,不悄悄扩大数据库合同。
|
||||
"""
|
||||
with pytest.raises(ValueError):
|
||||
NotificationChannel(identifier)
|
||||
Reference in New Issue
Block a user