fix(plugin): summarize market index probes per refresh

合并插件市场索引刷新汇总,减少已知回退探测的日志刷屏。
This commit is contained in:
jxxghp
2026-11-20 07:44:58 +08:00
committed by GitHub
13 changed files with 416 additions and 274 deletions

View File

@@ -885,14 +885,17 @@ class PluginMarketTransport(metaclass=WeakSingleton):
@staticmethod
def __plugin_index_log_source(source: Optional[str]) -> str:
"""
生成失败日志使用的有界来源标识,去掉凭据、缓存穿透参数并限制长度。
生成索引日志使用的有界来源标识,去掉凭据和缓存穿透参数。
"""
if not isinstance(source, str):
return ""
label = source.strip()
if not label:
return ""
parts = urlsplit(label)
try:
parts = urlsplit(label)
except ValueError:
return ""
if "@" in parts.netloc:
parts = parts._replace(netloc=parts.netloc.rsplit("@", 1)[-1])
if parts.query:
@@ -910,7 +913,7 @@ class PluginMarketTransport(metaclass=WeakSingleton):
@classmethod
def __plugin_index_log_suffix(cls, source: Optional[str]) -> str:
"""
把索引来源追加到警告文案;没有来源时保持原有日志不变。
把索引来源追加到诊断文案;没有来源时保持原有日志不变。
"""
label = cls.__plugin_index_log_source(source)
return f"(来源:{label})" if label else ""
@@ -920,27 +923,31 @@ class PluginMarketTransport(metaclass=WeakSingleton):
cls,
content: str,
source: Optional[str] = None,
*,
remote_probe: bool = False,
) -> Optional[PluginIndex]:
"""
解析并规范化插件索引,兼容 BOM 与 plugins 列表包装格式。
:param content: 已限长的索引响应文本
:param source: 可选索引来源,仅用于失败日志定位仓库或本地文件
:param source: 可选索引来源,仅用于日志定位仓库或本地文件
:param remote_probe: 远程探测的读取失败只记录调试明细,交由上层汇总
"""
suffix = cls.__plugin_index_log_suffix(source)
log_failure = logger.debug if remote_probe else logger.warning
try:
payload = json.loads(content.lstrip("\ufeff"))
except (ValueError, RecursionError):
logger.warning(f"插件包数据解析失败:响应不是有效 JSON{suffix}")
log_failure(f"插件包数据解析失败:响应不是有效 JSON{suffix}")
return None
if not isinstance(payload, dict):
logger.warning(
log_failure(
f"插件包数据格式不正确,期望 dict,实际为 {type(payload).__name__}{suffix}"
)
return None
if not cls.__plugin_index_nesting_is_valid(payload):
logger.warning(
log_failure(
f"插件包 JSON 嵌套超过上限:{PLUGIN_INDEX_MAX_NESTING} 层{suffix}"
)
return None
@@ -960,7 +967,7 @@ class PluginMarketTransport(metaclass=WeakSingleton):
plugin_entries = list(payload.items())
if len(plugin_entries) > PLUGIN_INDEX_MAX_ENTRIES:
logger.warning(
log_failure(
f"插件包条目超过上限:{len(plugin_entries)} > "
f"{PLUGIN_INDEX_MAX_ENTRIES}{suffix}"
)
@@ -1115,6 +1122,8 @@ class PluginMarketTransport(metaclass=WeakSingleton):
"""
按 GitHub 降级顺序流式读取并验证同步插件索引。
逐出口明细保留在调试日志,索引结果由调用方按仓库汇总。
:param url: GitHub 原始索引地址
:param headers: 仓库请求头
:param timeout: 单出口请求超时秒数
@@ -1128,8 +1137,9 @@ class PluginMarketTransport(metaclass=WeakSingleton):
)
for strategy_name, target_url, request_params in strategies:
from_mirror = strategy_name == "镜像站"
log_source = cls.__plugin_index_log_source(target_url)
logger.debug(
f"[GitHub] 尝试使用策略:{strategy_name} 请求插件索引:{target_url}"
f"[GitHub] 尝试使用策略:{strategy_name} 请求插件索引:{log_source}"
)
try:
request = RequestUtils(**request_params)
@@ -1146,12 +1156,15 @@ class PluginMarketTransport(metaclass=WeakSingleton):
except _PluginIndexReadError as error:
if not from_mirror:
raise
logger.warning(f"[GitHub] 镜像站未返回有效插件索引,将使用原始出口:{error}")
logger.debug(
f"[GitHub] 镜像站未返回有效插件索引,将使用原始出口:{error}({log_source})"
)
# 失败后尝试下一传输策略
except Exception as error: # noqa: BLE001
logger.error(
detail = _format_request_error(error).replace(target_url, log_source)
logger.debug(
f"[GitHub] 插件索引请求失败,策略:{strategy_name},"
f"URL:{target_url},错误:{_format_request_error(error)}"
f"URL:{log_source},错误:{detail}"
)
raise _PluginIndexUnavailableError("插件索引请求失败:连接失败")
@@ -1165,6 +1178,8 @@ class PluginMarketTransport(metaclass=WeakSingleton):
"""
按 GitHub 降级顺序流式读取并验证异步插件索引。
逐出口明细保留在调试日志,索引结果由调用方按仓库汇总。
:param url: GitHub 原始索引地址
:param headers: 仓库请求头
:param timeout: 单出口请求超时秒数
@@ -1178,8 +1193,9 @@ class PluginMarketTransport(metaclass=WeakSingleton):
)
for strategy_name, target_url, request_params in strategies:
from_mirror = strategy_name == "镜像站"
log_source = cls.__plugin_index_log_source(target_url)
logger.debug(
f"[GitHub] 尝试使用策略:{strategy_name} 请求插件索引:{target_url}"
f"[GitHub] 尝试使用策略:{strategy_name} 请求插件索引:{log_source}"
)
try:
request = AsyncRequestUtils(**request_params)
@@ -1199,12 +1215,15 @@ class PluginMarketTransport(metaclass=WeakSingleton):
except _PluginIndexReadError as error:
if not from_mirror:
raise
logger.warning(f"[GitHub] 镜像站未返回有效插件索引,将使用原始出口:{error}")
logger.debug(
f"[GitHub] 镜像站未返回有效插件索引,将使用原始出口:{error}({log_source})"
)
# 失败后尝试下一传输策略
except Exception as error: # noqa: BLE001
logger.error(
detail = _format_request_error(error).replace(target_url, log_source)
logger.debug(
f"[GitHub] 插件索引请求失败,策略:{strategy_name},"
f"URL:{target_url},错误:{_format_request_error(error)}"
f"URL:{log_source},错误:{detail}"
)
raise _PluginIndexUnavailableError("插件索引请求失败:连接失败")
@@ -1253,7 +1272,7 @@ class PluginMarketTransport(metaclass=WeakSingleton):
return None
if status_code != 200:
raise _PluginIndexUnavailableError(f"插件索引请求失败:HTTP {status_code}")
payload = cls.__parse_plugin_index_response(content, source=source)
payload = cls.__parse_plugin_index_response(content, source=source, remote_probe=True)
if payload is None:
raise _PluginIndexReadError("插件索引响应格式无效")
return payload

View File

@@ -6,6 +6,7 @@ from __future__ import annotations
import asyncio
import concurrent.futures
from collections import Counter
from collections.abc import Awaitable, Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any, Literal, Optional
@@ -43,18 +44,36 @@ class PluginMarketUnavailableError(RuntimeError):
@dataclass(frozen=True, slots=True)
class _CatalogLoadRequest:
class _CatalogIndexRead:
"""
冻结同步与异步插件市场加载共用的仓库和代际参数。
保留一次仓库索引读取的终态和投影结果。
:param market: 本次读取的配置市场地址
:param package_version: 请求读取的插件包代际;None 使用入口默认代际
:param force: 是否忽略本次读取或安装的缓存与版本短路
:param market: 配置市场地址
:param package_version: 索引代际;None 表示基础索引
:param plugins: 索引存在时映射出的候选,可以为空;None 表示没有可用索引
:param error: 读取失败的原因;没有索引且无错误时表示已确认缺失
"""
market: str
package_version: Optional[str]
force: bool
plugins: Optional[list[Any]] = None
error: Optional[str] = None
@property
def generation(self) -> str:
"""
返回汇总日志使用的代际名称。
"""
return self.package_version or "v1"
@classmethod
def failed(
cls, market: str, package_version: Optional[str], error: Exception,
) -> _CatalogIndexRead:
"""
记录读取失败,异常没有消息时也保留可诊断的类型。
"""
return cls(market, package_version, error=str(error).strip() or type(error).__name__)
def apply_declared_metadata_fallback(
@@ -123,7 +142,7 @@ def apply_declared_metadata_fallback(
class PluginCatalogService:
"""
负责插件市场索引映射、并发收集、代际合并和来源去重。
负责插件市场索引映射、并发收集、刷新汇总和代际合并。
"""
def __init__(
@@ -137,10 +156,11 @@ class PluginCatalogService:
version_compare: Callable[[str, str, str], bool],
warning: Callable[[str], Any],
error: Callable[[str], Any],
info: Callable[[str], Any],
max_concurrency: int = DEFAULT_MARKET_FETCH_CONCURRENCY,
) -> None:
"""
保存市场读取、插件映射和版本比较端口。
保存市场读取、插件映射和日志回调。索引不存在时读取端口返回 None,失败时抛出异常。
"""
if max_concurrency < 1:
raise ValueError("插件市场读取并发必须大于 0")
@@ -152,46 +172,62 @@ class PluginCatalogService:
self._version_compare = version_compare
self._warning = warning
self._error = error
self._info = info
self._max_concurrency = max_concurrency
@staticmethod
def _load_request(
def _index_read(
self,
market: str,
package_version: Optional[str],
payload: Optional[dict[str, dict[str, Any]]],
) -> _CatalogIndexRead:
"""
只映射确实存在的索引,保留有效空索引与缺失索引的区别。
"""
return _CatalogIndexRead(
market, package_version,
None if payload is None else self._map_plugins(payload, market, package_version),
)
def _read_index(
self,
market: str,
package_version: Optional[str],
force: bool,
) -> Optional[_CatalogLoadRequest]:
) -> _CatalogIndexRead:
"""
统一拒绝空市场,并冻结一次目录加载的完整输入。
同步读取单个索引,收集预期的传输或解析失败,不提前写日志。
"""
if not market:
return None
return _CatalogLoadRequest(
market=market,
package_version=package_version,
force=force,
)
try:
payload = self._market_loader(market, package_version, force)
except (ValueError, RuntimeError) as error:
return _CatalogIndexRead.failed(market, package_version, error)
return self._index_read(market, package_version, payload)
def _loaded_plugins(
async def _async_read_index(
self,
request: _CatalogLoadRequest,
online_plugins: Optional[dict[str, dict[str, Any]]],
) -> Optional[list[Any]]:
market: str,
package_version: Optional[str],
force: bool,
) -> _CatalogIndexRead:
"""
统一加载失败告警与在线目录到插件 DTO 的投影。
异步读取单个索引,保留成功、缺失和失败三种结果供目录使用。
"""
try:
payload = await self._async_market_loader(market, package_version, force)
except (ValueError, RuntimeError) as error:
return _CatalogIndexRead.failed(market, package_version, error)
return self._index_read(market, package_version, payload)
:param request: 本次读取的市场和代际参数
:param online_plugins: 已读取的索引;None 表示传输或解析失败
:return: 映射后的插件目录;索引读取失败时返回 None
def _single_index_plugins(self, read: _CatalogIndexRead) -> list[Any]:
"""
if online_plugins is None:
单独查询某一代索引时就地记录读取失败,仍返回兼容的空列表。
"""
if read.error is not None:
self._warning(
f"获取{request.package_version if request.package_version else ''}插件库失败:"
f"{request.market},请检查 GitHub 网络连接"
f"获取 {read.generation} 插件索引失败:{read.market},{read.error}"
)
return None
return self._map_plugins(
online_plugins, request.market, request.package_version
)
return read.plugins or []
def load(
self,
@@ -202,17 +238,9 @@ class PluginCatalogService:
"""
同步读取并映射指定市场和插件代际。
"""
request = PluginCatalogService._load_request(
market, package_version, force
)
if request is None:
if not market:
return []
return self._loaded_plugins(
request,
self._market_loader(
request.market, request.package_version, request.force
),
) or []
return self._single_index_plugins(self._read_index(market, package_version, force))
async def async_load(
self,
@@ -228,33 +256,55 @@ class PluginCatalogService:
:param force: 是否跳过读取缓存
:return: 映射后的插件目录,读取失败时为空
"""
return await self.async_read(market, package_version, force) or []
async def async_read(
self,
market: str,
package_version: Optional[str] = None,
force: bool = False,
) -> Optional[list[Any]]:
"""
异步读取并映射指定索引,保留失败状态供市场聚合使用。
:param market: 插件市场仓库地址
:param package_version: 要读取的索引代际;None 表示基础索引
:param force: 是否跳过读取缓存
:return: 映射后的插件目录,读取失败时返回 None
"""
request = PluginCatalogService._load_request(
market, package_version, force
)
if request is None:
if not market:
return []
online_plugins = await self._async_market_loader(
request.market,
request.package_version,
request.force,
return self._single_index_plugins(await self._async_read_index(market, package_version, force))
def _log_index_refresh(
self,
reads: Sequence[_CatalogIndexRead],
compatible_flags: Sequence[str],
plugin_count: int,
) -> None:
"""
汇总一轮索引探测,只为没有任何可用索引的仓库写单独错误。
:param reads: 按配置仓库和代际读取顺序排列的终态
:param compatible_flags: 兼容代际按优先级排列;最后才考虑基础索引
:param plugin_count: 合并后的线上插件数
"""
if not reads:
return
reads_by_market: dict[str, list[_CatalogIndexRead]] = {}
for read in reads:
reads_by_market.setdefault(read.market, []).append(read)
missing = Counter(read.generation for read in reads if read.plugins is None and read.error is None)
failures = Counter(read.generation for read in reads if read.error is not None)
generations = [*compatible_flags, "v1"]
available = 0
fallback = 0
for market, market_reads in reads_by_market.items():
present = {read.generation for read in market_reads if read.plugins is not None}
if present:
available += 1
fallback += generations[0] not in present
continue
details = ";".join(f"{read.generation} {read.error or '未发布'}" for read in market_reads)
self._error(f"插件仓库未取得任何索引:{market}({details})")
total = len(reads_by_market)
self._info(
f"插件索引探测完成:共 {total} 个仓库,{available} 个可用,{total - available} 个无可用索引,"
f"{fallback} 个回退到较低代际;缺少索引 {self._format_index_counts(missing, generations)};"
f"读取失败 {self._format_index_counts(failures, generations)};获取到 {plugin_count} 个线上插件"
)
return self._loaded_plugins(request, online_plugins)
@staticmethod
def _format_index_counts(counts: Counter[str], generations: Sequence[str]) -> str:
"""
按代际优先级呈现探测次数,省略为零的代际。
"""
details = " / ".join(f"{generation} {counts[generation]}" for generation in generations if counts[generation])
return f"{counts.total()} 次({details})" if details else "0 次"
def collect(
self,
@@ -262,51 +312,50 @@ class PluginCatalogService:
markets: list[str],
compatible_flags: list[str],
force: bool,
loader: Callable[[str, Optional[str], bool], list[Any]],
) -> list[Any]:
"""
并发读取多个市场和代际,并按稳定优先级合并。
并发读取多个市场及代际,汇总本轮结果并按稳定优先级合并。
"""
with concurrent.futures.ThreadPoolExecutor(
max_workers=self._max_concurrency
) as executor:
futures_meta: dict[
concurrent.futures.Future[Any],
tuple[int, bool, int],
concurrent.futures.Future[_CatalogIndexRead],
tuple[int, str, Optional[str]],
] = {}
for market_index, market in enumerate(markets):
base_future = executor.submit(loader, market, None, force)
futures_meta[base_future] = (market_index, False, 0)
for flag_priority, flag in enumerate(compatible_flags):
higher_future = executor.submit(loader, market, flag, force)
futures_meta[higher_future] = (
market_index,
True,
flag_priority,
)
for market in markets:
base_future = executor.submit(self._read_index, market, None, force)
futures_meta[base_future] = (len(futures_meta), market, None)
for flag in compatible_flags:
higher_future = executor.submit(self._read_index, market, flag, force)
futures_meta[higher_future] = (len(futures_meta), market, flag)
collected = []
collected: dict[int, _CatalogIndexRead] = {}
for future in concurrent.futures.as_completed(futures_meta):
index, market, generation = futures_meta[future]
try:
plugins = future.result()
# 单个市场失败不能中断全量刷新
collected[index] = future.result()
# 投影等意外异常也不能中断整个刷新
except Exception as error: # noqa: BLE001
self._error(f"获取插件市场数据失败:{str(error)}")
plugins = []
market_index, is_higher, flag_priority = futures_meta[future]
collected.append((
market_index,
is_higher,
flag_priority,
plugins or [],
))
collected[index] = _CatalogIndexRead.failed(market, generation, error)
collected.sort(key=lambda item: (item[0], 0 if item[1] else 1, item[2]))
reads = [collected[index] for index in sorted(collected)]
higher_plugins, base_plugins = self._split_index_plugins(reads)
result = self.merge(higher_plugins, base_plugins, markets)
self._log_index_refresh(reads, compatible_flags, len(result))
return result
@staticmethod
def _split_index_plugins(reads: Sequence[_CatalogIndexRead]) -> tuple[list[Any], list[Any]]:
"""
按原有顺序拆出高代际和基础索引的候选,供目录合并。
"""
higher_plugins: list[Any] = []
base_plugins: list[Any] = []
for _market_index, is_higher, _flag_priority, plugins in collected:
(higher_plugins if is_higher else base_plugins).extend(plugins)
return self.merge(higher_plugins, base_plugins, markets)
for read in reads:
target = higher_plugins if read.package_version is not None else base_plugins
target.extend(read.plugins or [])
return higher_plugins, base_plugins
@staticmethod
def _require_available_market_candidates(
@@ -336,10 +385,6 @@ class PluginCatalogService:
markets: list[str],
compatible_flags: list[str],
force: bool,
loader: Callable[
[str, Optional[str], bool],
Awaitable[Optional[list[Any]]],
],
preserve_sources: bool = False,
require_available: bool = False,
progress_callback: Optional[ProgressCallback] = None,
@@ -350,7 +395,6 @@ class PluginCatalogService:
:param markets: 本轮读取的仓库地址,顺序决定合并优先级
:param compatible_flags: 要读取的插件代际及其优先级
:param force: 是否跳过索引缓存
:param loader: 单个市场和代际的异步读取入口;失败时返回 None 或抛错
:param preserve_sources: 是否保留每个仓库的候选,不跨仓去重
:param require_available: 是否在没有候选且有索引读取失败时报告市场不可用
:param progress_callback: 可选的进度更新回调
@@ -362,32 +406,33 @@ class PluginCatalogService:
async def fetch(
market: str,
package_version: Optional[str],
result_version: str,
task_index: int,
) -> tuple[int, str, Optional[list[Any]]]:
) -> tuple[int, _CatalogIndexRead]:
"""
读取一个市场代际并保留创建时的稳定任务序号。
"""
async with semaphore:
plugins = await loader(market, package_version, force)
return task_index, result_version, plugins
try:
read = await self._async_read_index(market, package_version, force)
# 投影等意外异常也不能中断整个刷新
except Exception as error: # noqa: BLE001
read = _CatalogIndexRead.failed(market, package_version, error)
return task_index, read
tasks: list[asyncio.Task[tuple[int, str, Optional[list[Any]]]]] = []
tasks: list[asyncio.Task[tuple[int, _CatalogIndexRead]]] = []
for market in markets:
tasks.append(asyncio.create_task(
fetch(market, None, "base_version", len(tasks)),
fetch(market, None, len(tasks)),
name="plugin.catalog.fetch",
))
for flag in compatible_flags:
tasks.append(asyncio.create_task(
fetch(market, flag, "higher_version", len(tasks)),
fetch(market, flag, len(tasks)),
name="plugin.catalog.fetch",
))
try:
higher_plugins: list[Any] = []
base_plugins: list[Any] = []
task_results: dict[int, tuple[str, list[Any]]] = {}
task_results: dict[int, _CatalogIndexRead] = {}
if tasks:
total_tasks = len(tasks)
finished_tasks = 0
@@ -398,12 +443,8 @@ class PluginCatalogService:
data={"total": total_tasks, "finished": 0},
)
for completed_task in asyncio.as_completed(tasks):
try:
task_index, version, plugins = await completed_task
if plugins is not None:
task_results[task_index] = (version, plugins)
except Exception as err:
self._error(f"获取插件市场数据失败:{str(err)}")
task_index, read = await completed_task
task_results[task_index] = read
finished_tasks += 1
if progress_callback:
progress_callback(
@@ -414,21 +455,19 @@ class PluginCatalogService:
),
data={"total": total_tasks, "finished": finished_tasks},
)
for task_index in sorted(task_results):
version, plugins = task_results[task_index]
target = higher_plugins if version == "higher_version" else base_plugins
target.extend(plugins)
reads = [task_results[index] for index in sorted(task_results)]
higher_plugins, base_plugins = self._split_index_plugins(reads)
result = (
self.merge_by_source(higher_plugins, base_plugins, markets)
if preserve_sources
else self.merge(higher_plugins, base_plugins, markets)
)
self._log_index_refresh(reads, compatible_flags, len(result))
self._require_available_market_candidates(
required=require_available,
candidates=result,
expected_reads=len(tasks),
successful_reads=len(task_results),
successful_reads=sum(read.error is None for read in reads),
)
if progress_callback:
progress_callback(value=100, text="插件市场缓存刷新完成")

View File

@@ -32,8 +32,6 @@ class PluginCatalogFacade:
storage: Callable[[], PluginStorage],
system: Callable[[], PluginSystemServices],
market_catalog: Callable[[], Any],
market_loader: Callable[..., Any],
async_market_loader: Callable[..., Any],
map_plugin: Callable[..., Optional[Plugin]],
auth_checker: Callable[..., bool],
plugin_attr: Callable[[str, str], Any],
@@ -51,8 +49,6 @@ class PluginCatalogFacade:
self._storage = storage
self._system = system
self._market_catalog = market_catalog
self._market_loader = market_loader
self._async_market_loader = async_market_loader
self._map_plugin = map_plugin
self._auth_checker = auth_checker
self._plugin_attr = plugin_attr
@@ -76,9 +72,7 @@ class PluginCatalogFacade:
get_runtime_setting('VERSION_FLAG')
),
force=force,
loader=self._market_loader,
)
self._logger.info(f"获取到 {len(result)} 个线上插件")
return result
def local(self) -> list[Plugin]:
@@ -311,10 +305,8 @@ class PluginCatalogFacade:
get_runtime_setting('VERSION_FLAG')
),
force=force,
loader=self._async_market_loader,
progress_callback=progress_callback,
)
self._logger.info(f"获取到 {len(result)} 个线上插件")
return result
async def async_online_candidates(
@@ -337,14 +329,12 @@ class PluginCatalogFacade:
markets = [market for market in markets if target and market.lower() == target.lower()]
if not markets:
return []
market_catalog = self._market_catalog()
result: list[Plugin] = await market_catalog.async_collect(
result: list[Plugin] = await self._market_catalog().async_collect(
markets=markets,
compatible_flags=self._system().compatible_flags(
get_runtime_setting('VERSION_FLAG')
),
force=force,
loader=market_catalog.async_read if repo_url is None else self._async_market_loader,
preserve_sources=True,
require_available=repo_url is None,
)

View File

@@ -87,38 +87,6 @@ class PluginRuntimeHost(Protocol):
"""
...
def get_plugins_from_market(
self,
market: str,
package_version: Optional[str] = None,
force: bool = False,
) -> Optional[list[Any]]:
"""
读取指定市场目录。
:param market: 插件市场地址
:param package_version: 限定的插件代际;为 None 时按当前主程序兼容范围读取
:param force: 是否跳过目录缓存并重新获取,默认使用缓存
:return: 可用的插件目录条目;获取失败或没有可用目录时可返回 None
"""
...
async def async_get_plugins_from_market(
self,
market: str,
package_version: Optional[str] = None,
force: bool = False,
) -> Optional[list[Any]]:
"""
异步读取指定市场目录。
:param market: 插件市场地址
:param package_version: 限定的插件代际;为 None 时按当前主程序兼容范围读取
:param force: 是否跳过目录缓存并重新获取,默认使用缓存
:return: 等待后取得插件目录条目;获取失败或没有可用目录时可返回 None
"""
...
PluginCatalogFactory = Callable[[Callable[..., Any]], Any]
PluginImportService = Callable[..., None]
@@ -354,16 +322,6 @@ def build_plugin_runtime(
storage=environment.storage,
system=environment.system,
market_catalog=lambda: environment.catalog_factory(metadata.map),
market_loader=lambda market, package_version=None, force=False: (
host.get_plugins_from_market(market, package_version, force)
),
async_market_loader=lambda market, package_version=None, force=False: (
host.async_get_plugins_from_market(
market,
package_version,
force,
)
),
map_plugin=lambda **kwargs: metadata.map(
plugin_id=kwargs["pid"],
plugin_info=kwargs["plugin_info"],

View File

@@ -973,8 +973,8 @@ def _build_plugin_catalog(plugin_mapper: Callable[..., Any]) -> PluginCatalogSer
client = get_composed_plugin_market_client()
return PluginCatalogService(
market_loader=client.get_plugins,
async_market_loader=client.async_get_plugins,
market_loader=client.get_plugin_index_result,
async_market_loader=client.async_get_plugin_index_result,
installed_plugins_provider=lambda: get_configured_system_config().get(
SystemConfigKey.UserInstalledPlugins
) or [],
@@ -983,6 +983,7 @@ def _build_plugin_catalog(plugin_mapper: Callable[..., Any]) -> PluginCatalogSer
version_compare=version_matches,
warning=logger.warning,
error=logger.error,
info=logger.info,
)

View File

@@ -19,8 +19,8 @@ def test_catalog_version_comparison_accepts_only_explicit_success(
:param monkeypatch: 用无网络客户端隔离市场读取
"""
client = SimpleNamespace(
get_plugins=lambda *_args, **_kwargs: [],
async_get_plugins=AsyncMock(return_value=[]),
get_plugin_index_result=lambda *_args, **_kwargs: {},
async_get_plugin_index_result=AsyncMock(return_value={}),
)
monkeypatch.setattr(
plugins_initializer, "get_composed_plugin_market_client", lambda: client

View File

@@ -14,20 +14,24 @@ from app.application.plugin.catalog import PluginCatalogService
def _catalog(
max_concurrency: int = 2,
*,
market_loader: Callable = lambda *_args: {},
async_market_loader: Callable = lambda *_args: {},
error: Callable[[str], None] | None = None,
) -> PluginCatalogService:
"""
构造不依赖真实插件目录和网络的目录服务。
"""
return PluginCatalogService(
market_loader=lambda *_args: {},
async_market_loader=lambda *_args: {},
market_loader=market_loader,
async_market_loader=async_market_loader,
installed_plugins_provider=lambda: [],
plugin_mapper=lambda *_args, **_kwargs: None,
is_local_repo=lambda _repo_url: False,
version_compare=lambda *_args: False,
warning=lambda *_args: None,
error=error if error is not None else lambda *_args: None,
info=lambda *_args: None,
max_concurrency=max_concurrency,
)
@@ -42,6 +46,9 @@ def test_sync_collect_limits_market_fetch_concurrency() -> None:
calls: list[tuple[str, str | None, bool]] = []
def loader(market: str, package_version: str | None, force: bool):
"""
记录每次同步读取的并发峰值。
"""
nonlocal active, peak
with lock:
active += 1
@@ -50,13 +57,12 @@ def test_sync_collect_limits_market_fetch_concurrency() -> None:
time.sleep(0.01)
with lock:
active -= 1
return []
return {}
result = _catalog(max_concurrency=2).collect(
result = _catalog(max_concurrency=2, market_loader=loader).collect(
markets=["market-a", "market-b", "market-c"],
compatible_flags=["v3"],
force=True,
loader=loader,
)
assert result == []
@@ -75,19 +81,22 @@ def test_sync_collect_isolates_market_failure() -> None:
package_version: str | None,
_force: bool,
):
if market == "market-b" and package_version == "v3":
"""
让一个仓库所有代际失败,其余仓库仍可返回有效空索引。
"""
if market == "market-b":
raise RuntimeError("market unavailable")
return []
return {}
result = _catalog(max_concurrency=2, error=errors.append).collect(
result = _catalog(max_concurrency=2, market_loader=loader, error=errors.append).collect(
markets=["market-a", "market-b"],
compatible_flags=["v3"],
force=True,
loader=loader,
)
assert result == []
assert len(errors) == 1
assert "market-b" in errors[0]
assert "market unavailable" in errors[0]
@@ -100,18 +109,20 @@ async def test_async_collect_limits_market_fetch_concurrency() -> None:
peak = 0
async def loader(_market: str, _package_version: str | None, _force: bool):
"""
记录同时在途的异步索引读取数。
"""
nonlocal active, peak
active += 1
peak = max(peak, active)
await asyncio.sleep(0.01)
active -= 1
return []
return {}
result = await _catalog(max_concurrency=2).async_collect(
result = await _catalog(max_concurrency=2, async_market_loader=loader).async_collect(
markets=["market-a", "market-b", "market-c"],
compatible_flags=["v3"],
force=True,
loader=loader,
)
assert result == []

View File

@@ -36,8 +36,6 @@ def _facade(**overrides):
),
system=lambda: SimpleNamespace(),
market_catalog=lambda: None,
market_loader=lambda *_args, **_kwargs: [],
async_market_loader=lambda *_args, **_kwargs: [],
map_plugin=lambda **_kwargs: None,
auth_checker=lambda **_kwargs: True,
plugin_attr=lambda _plugin_id, _attr: None,
@@ -78,15 +76,16 @@ async def test_source_candidates_only_load_selected_configured_repository(monkey
@pytest.mark.asyncio
async def test_catalog_warns_when_market_candidates_cannot_be_loaded(monkeypatch):
async def test_catalog_reports_when_market_candidates_cannot_be_loaded(monkeypatch):
"""
全市场查询保留索引失败,单仓文档查询继续返回空候选。
"""
from app.runtime.extensions.plugin import catalog as catalog_module
repo = "https://github.com/Example/Plugins"
warnings: list[str] = []
loader = AsyncMock(return_value=None)
errors: list[str] = []
info: list[str] = []
loader = AsyncMock(side_effect=RuntimeError("索引请求失败"))
service = PluginCatalogService(
market_loader=lambda *_args: None,
async_market_loader=loader,
@@ -94,8 +93,9 @@ async def test_catalog_warns_when_market_candidates_cannot_be_loaded(monkeypatch
plugin_mapper=lambda *_args: None,
is_local_repo=lambda _value: False,
version_compare=lambda *_args: False,
warning=warnings.append,
error=warnings.append,
warning=lambda message: pytest.fail(message),
error=errors.append,
info=info.append,
)
monkeypatch.setattr(catalog_module, "get_runtime_setting", lambda key: {
"PLUGIN_MARKET": repo,
@@ -104,7 +104,6 @@ async def test_catalog_warns_when_market_candidates_cannot_be_loaded(monkeypatch
facade = _facade(
system=lambda: SimpleNamespace(compatible_flags=lambda _flag: ["v3"]),
market_catalog=lambda: service,
async_market_loader=service.async_load,
)
with pytest.raises(PluginMarketUnavailableError, match="插件市场索引暂时无法读取"):
@@ -112,7 +111,8 @@ async def test_catalog_warns_when_market_candidates_cannot_be_loaded(monkeypatch
loader.assert_any_await(repo, "v3", True)
assert await facade.async_online_candidates(repo_url=repo) == []
assert len(warnings) == 4
assert len(errors) == len(info) == 2
assert all(repo in error for error in errors)
@pytest.mark.asyncio
@@ -154,8 +154,6 @@ async def test_async_online_normalizes_market_configuration(monkeypatch) -> None
compatible_flags=lambda _flag: [],
),
market_catalog=lambda: FakeMarketCatalog(),
market_loader=lambda *_args, **_kwargs: [],
async_market_loader=lambda *_args, **_kwargs: [],
map_plugin=lambda **_kwargs: None,
auth_checker=lambda **_kwargs: True,
plugin_attr=lambda _plugin_id, _attr: None,
@@ -200,8 +198,6 @@ def test_installed_catalog_keeps_plugins_that_are_not_loaded():
),
system=lambda: SimpleNamespace(),
market_catalog=lambda: None,
market_loader=lambda *_args, **_kwargs: [],
async_market_loader=lambda *_args, **_kwargs: [],
map_plugin=lambda **_kwargs: None,
auth_checker=lambda **_kwargs: True,
plugin_attr=lambda _plugin_id, _attr: None,
@@ -248,8 +244,6 @@ def test_local_repository_failure_does_not_break_catalog_projection():
local_candidates=local_candidates,
),
market_catalog=lambda: None,
market_loader=lambda *_args, **_kwargs: [],
async_market_loader=lambda *_args, **_kwargs: [],
map_plugin=lambda **_kwargs: None,
auth_checker=lambda **_kwargs: True,
plugin_attr=lambda _plugin_id, _attr: None,

View File

@@ -40,7 +40,7 @@ def _service(**overrides) -> PluginCatalogService:
"""
defaults = {
"market_loader": Mock(return_value={}),
"async_market_loader": Mock(),
"async_market_loader": AsyncMock(return_value={}),
"installed_plugins_provider": Mock(return_value=[]),
"plugin_mapper": Mock(),
"is_local_repo": lambda value: str(value).startswith("local://"),
@@ -50,6 +50,7 @@ def _service(**overrides) -> PluginCatalogService:
),
"warning": Mock(),
"error": Mock(),
"info": Mock(),
}
defaults.update(overrides)
return PluginCatalogService(**defaults)
@@ -194,8 +195,6 @@ async def test_async_collect_isolates_failure_and_completes_progress():
"""
progress = Mock()
error = Mock()
service = _service(error=error)
async def loader(market: str, package_version: str | None, _force: bool):
"""
模拟一个失败代际和其余可正常完成的市场请求。
@@ -205,13 +204,19 @@ async def test_async_collect_isolates_failure_and_completes_progress():
raise RuntimeError("unavailable")
version = "2.0.0" if package_version else "1.0.0"
plugin_id = "MarketA" if market.endswith("market-a") else "MarketB"
return [_plugin(plugin_id, version, market)]
return {plugin_id: {"version": version}}
service = _service(
async_market_loader=loader,
plugin_mapper=lambda plugin_id, info, market, _installed, _time, generation: (
_plugin(plugin_id, info["version"], market, generation)
),
error=error,
)
result = await service.async_collect(
markets=["https://market-a", "https://market-b"],
compatible_flags=["v3"],
force=True,
loader=loader,
require_available=True,
progress_callback=progress,
)
@@ -220,21 +225,23 @@ async def test_async_collect_isolates_failure_and_completes_progress():
"MarketA",
"MarketB",
}
error.assert_called_once()
error.assert_not_called()
assert progress.call_args_list[0].kwargs["value"] == 0
assert progress.call_args_list[-1].kwargs["value"] == 100
@pytest.mark.asyncio
@pytest.mark.parametrize("base_index", [None, {}], ids=["all-failed", "base-absent"])
@pytest.mark.parametrize("base_index", [None, {}], ids=["base-absent", "base-empty"])
async def test_async_collect_reports_failure_without_candidates(base_index):
"""
没有候选且存在读取失败时报告市场不可用,已确认缺少基础索引也不能掩盖失败。
"""
warnings = Mock()
errors = Mock()
summary = Mock()
service = _service(
async_market_loader=AsyncMock(side_effect=[base_index, None, None]),
warning=warnings,
async_market_loader=AsyncMock(side_effect=[base_index, RuntimeError("timeout"), None]),
error=errors,
info=summary,
)
with pytest.raises(PluginMarketUnavailableError, match="插件市场索引暂时无法读取"):
@@ -242,11 +249,97 @@ async def test_async_collect_reports_failure_without_candidates(base_index):
markets=["https://market-a"],
compatible_flags=["v3", "v2"],
force=False,
loader=service.async_read,
require_available=True,
)
assert warnings.call_count == (3 if base_index is None else 2)
summary.assert_called_once()
if base_index is None:
errors.assert_called_once()
assert "https://market-a" in errors.call_args.args[0]
else:
errors.assert_not_called()
@pytest.mark.asyncio
@pytest.mark.parametrize("mode", ["sync", "async"])
async def test_market_refresh_summarizes_index_probes_by_repository(mode):
"""
每轮只汇总一次,回退和空索引无需报错,整个仓库不可用时只报一次。
"""
v2_repo, v1_repo, empty_repo, broken_repo, missing_repo = (
f"https://github.com/market-test/{name}"
for name in ("v2", "v1", "empty", "broken", "missing")
)
markets = [v2_repo, v1_repo, empty_repo, broken_repo, missing_repo]
outcomes = {
(v2_repo, "v2"): {"Modern": {"version": "1.0.0"}},
(v2_repo, None): {"Other": {"version": "1.0.0"}},
(v1_repo, "v3"): TimeoutError("直连超时"),
(v1_repo, None): {"Legacy": {"version": "1.0.0"}},
(empty_repo, "v3"): {},
(broken_repo, "v3"): RuntimeError("响应格式无效"),
(broken_repo, "v2"): RuntimeError("HTTP 503"),
}
warning, error, info = Mock(), Mock(), Mock()
def load(market: str, generation: str | None, force: bool):
"""
为每个仓库代际返回索引、确认缺失,或抛出读取异常。
"""
assert force
outcome = outcomes.get((market, generation))
if isinstance(outcome, Exception):
raise outcome
return outcome
service = _service(
market_loader=Mock(side_effect=load),
async_market_loader=AsyncMock(side_effect=load),
plugin_mapper=lambda plugin_id, metadata, market, _installed, _time, generation: (
_plugin(plugin_id, metadata["version"], market, generation)
),
warning=warning,
error=error,
info=info,
)
kwargs = {"markets": markets, "compatible_flags": ["v3", "v2"], "force": True}
result = await service.async_collect(**kwargs) if mode == "async" else service.collect(**kwargs)
assert [(plugin.id, plugin.package_version) for plugin in result] == [
("Modern", "v2"), ("Other", None), ("Legacy", None),
]
warning.assert_not_called()
assert error.call_count == 2
assert broken_repo in error.call_args_list[0].args[0]
assert "v3 响应格式无效" in error.call_args_list[0].args[0]
assert "v2 HTTP 503" in error.call_args_list[0].args[0]
assert missing_repo in error.call_args_list[1].args[0]
info.assert_called_once()
summary = info.call_args.args[0]
assert "共 5 个仓库,3 个可用,2 个无可用索引,2 个回退到较低代际" in summary
assert "缺少索引 8 次(v3 2 / v2 3 / v1 3)" in summary
assert "读取失败 3 次(v3 2 / v2 1)" in summary
assert "获取到 3 个线上插件" in summary
@pytest.mark.asyncio
async def test_single_index_query_still_warns_without_a_refresh_summary():
"""
单代查询失败继续提示,确认缺失的索引则直接返回空目录。
"""
warning, info = Mock(), Mock()
service = _service(
market_loader=Mock(side_effect=RuntimeError("HTTP 503")),
async_market_loader=AsyncMock(return_value=None),
warning=warning,
info=info,
)
assert service.load("https://market-a", "v3") == []
assert await service.async_load("https://market-a", "v2") == []
warning.assert_called_once()
assert "HTTP 503" in warning.call_args.args[0]
info.assert_not_called()
@pytest.mark.asyncio
@@ -264,7 +357,6 @@ async def test_async_collect_keeps_valid_empty_market_results():
markets=["https://market-empty"],
compatible_flags=["v3"],
force=False,
loader=service.async_read,
require_available=True,
)
@@ -277,22 +369,25 @@ async def test_async_collect_preserves_each_repository_update_candidate():
"""
来源准入读取应保留每个仓库的最高版本,不能先按插件 ID 全局去重。
"""
service = _service()
async def loader(market: str, package_version: str | None, _force: bool):
"""
按仓库返回不同版本,验证来源保留模式不会提前跨仓去重。
"""
if package_version is None:
return []
return None
version = "2.0.0" if market == "https://market-bound" else "3.0.0"
return [_plugin("Demo", version, market)]
return {"Demo": {"version": version}}
service = _service(
async_market_loader=loader,
plugin_mapper=lambda plugin_id, info, market, _installed, _time, generation: (
_plugin(plugin_id, info["version"], market, generation)
),
)
result = await service.async_collect(
markets=["https://market-bound", "https://market-alternative"],
compatible_flags=["v3"],
force=False,
loader=loader,
preserve_sources=True,
)
@@ -308,7 +403,6 @@ async def test_async_collect_cancels_all_loaders_when_parent_is_cancelled():
"""
请求取消时必须取消并回收全部市场 loader,不能把子任务遗留在事件循环。
"""
service = _service()
blocker = asyncio.Event()
all_started = asyncio.Event()
started = 0
@@ -327,14 +421,15 @@ async def test_async_collect_cancels_all_loaders_when_parent_is_cancelled():
except asyncio.CancelledError:
cancelled += 1
raise
return []
return {}
summary = Mock()
service = _service(async_market_loader=loader, info=summary)
collect_task = asyncio.create_task(
service.async_collect(
markets=["https://market-a", "https://market-b"],
compatible_flags=[],
force=True,
loader=loader,
)
)
await asyncio.wait_for(all_started.wait(), timeout=1)
@@ -344,6 +439,7 @@ async def test_async_collect_cancels_all_loaders_when_parent_is_cancelled():
await collect_task
await asyncio.sleep(0)
assert cancelled == 2
summary.assert_not_called()
finally:
blocker.set()
await asyncio.sleep(0)
@@ -354,7 +450,6 @@ async def test_async_collect_cleans_loaders_when_progress_callback_fails():
"""
进度回调异常也必须取消并回收尚未完成的市场 loader。
"""
service = _service()
blocker = asyncio.Event()
slow_started = asyncio.Event()
slow_cancelled = asyncio.Event()
@@ -365,14 +460,14 @@ async def test_async_collect_cleans_loaders_when_progress_callback_fails():
"""
if market == "https://market-a":
await slow_started.wait()
return []
return {}
slow_started.set()
try:
await blocker.wait()
except asyncio.CancelledError:
slow_cancelled.set()
raise
return []
return {}
def progress(*, value: float, **_kwargs) -> None:
"""
@@ -381,13 +476,13 @@ async def test_async_collect_cleans_loaders_when_progress_callback_fails():
if value > 0:
raise RuntimeError("progress unavailable")
service = _service(async_market_loader=loader)
with pytest.raises(RuntimeError, match="progress unavailable"):
await asyncio.wait_for(
service.async_collect(
markets=["https://market-a", "https://market-b"],
compatible_flags=[],
force=True,
loader=loader,
progress_callback=progress,
),
timeout=1,

View File

@@ -61,6 +61,7 @@ def _query(candidates: list[Plugin], readme: AsyncMock) -> PluginCatalogQuery:
version_compare=lambda left, operator, right: compare_version(left, operator, right) is True,
warning=Mock(),
error=Mock(),
info=Mock(),
)
return PluginCatalogQuery(
installed_plugins=lambda: [],

View File

@@ -105,8 +105,8 @@ def _configure_plugin_catalog_factory(monkeypatch):
"""
client = PluginMarketClient()
return PluginCatalogService(
market_loader=client.get_plugins,
async_market_loader=client.async_get_plugins,
market_loader=client.get_plugin_index_result,
async_market_loader=client.async_get_plugin_index_result,
installed_plugins_provider=lambda: get_plugin_storage().read(
SystemConfigKey.UserInstalledPlugins
) or [],
@@ -115,6 +115,7 @@ def _configure_plugin_catalog_factory(monkeypatch):
version_compare=compare_version,
warning=manager_module.logger.warning,
error=manager_module.logger.error,
info=manager_module.logger.info,
)
monkeypatch.setattr(manager_module, "_plugin_catalog_factory", build_catalog)
@@ -934,7 +935,7 @@ class TestPluginHelper:
)
monkeypatch.setattr(
PluginMarketTransport,
"get_plugins",
"get_plugin_index_result",
lambda _self, *_args: market_plugins,
)
@@ -976,9 +977,11 @@ class TestPluginHelper:
}
def fake_get_plugins(_self, _repo_url, package_version=None):
# package.v3.json 不存在(404 → 空字典),package.v2.json 返回 v2 原生插件
"""
模拟 v3 索引缺失,同时保留 v2 和基础索引的候选。
"""
if package_version == "v3":
return {}
return None
if package_version == "v2":
return v2_native_plugins
return base_plugins
@@ -1004,7 +1007,7 @@ class TestPluginHelper:
"app.runtime.extensions.plugin.manager._site_auth_level_provider",
lambda: 1,
)
monkeypatch.setattr(PluginMarketTransport, "get_plugins", fake_get_plugins)
monkeypatch.setattr(PluginMarketTransport, "get_plugin_index_result", fake_get_plugins)
plugins = plugin_manager.get_online_plugins(force=False)
plugin_ids = {p.id for p in plugins}
@@ -1230,7 +1233,7 @@ class TestPluginHelper:
PLUGIN_MARKET="https://github.com/demo/plugins",
VERSION_FLAG="v3",
)
monkeypatch.setattr(PluginManager, "get_plugins_from_market", lambda *_args, **_kwargs: [])
monkeypatch.setattr(PluginMarketTransport, "get_plugin_index_result", lambda *_args, **_kwargs: {})
PluginManager().get_online_plugins(force=True)
@@ -1251,14 +1254,17 @@ class TestPluginHelper:
clear_calls.append("clear")
async def fake_market(*_args, **_kwargs):
return []
"""
模拟成功读取空索引,隔离真实的市场请求。
"""
return {}
_patch_catalog_settings(
monkeypatch,
PLUGIN_MARKET="https://github.com/demo/plugins",
VERSION_FLAG="v3",
)
monkeypatch.setattr(PluginManager, "async_get_plugins_from_market", fake_market)
monkeypatch.setattr(PluginMarketTransport, "async_get_plugin_index_result", fake_market)
asyncio.run(PluginManager().async_get_online_plugins(force=True))

View File

@@ -366,6 +366,10 @@ async def test_plugin_index_fallback_checks_response_before_accepting_it(
"""
只有可解析索引或原始出口的 404 可以结束降级;镜像失败后仍保留原始出口的结果。
"""
debug, warning, error = Mock(), Mock(), Mock()
monkeypatch.setattr(plugin_client_module.logger, "debug", debug)
monkeypatch.setattr(plugin_client_module.logger, "warning", warning)
monkeypatch.setattr(plugin_client_module.logger, "error", error)
settings = {
"GITHUB_PROXY": "https://mirror.example",
"PROXY_HOST": None,
@@ -380,7 +384,7 @@ async def test_plugin_index_fallback_checks_response_before_accepting_it(
index_url = "https://raw.githubusercontent.com/example/repo/main/package.v3.json"
mirror_url = f"https://mirror.example/{index_url}"
def response_for(url: str) -> tuple[int, bytes] | None:
def response_for(url: str) -> tuple[int, bytes]:
"""
记录出口顺序并按实际请求地址选择离线响应。
"""
@@ -389,7 +393,7 @@ async def test_plugin_index_fallback_checks_response_before_accepting_it(
return mirror
assert url == index_url
if origin_status is None:
return None
raise TimeoutError("直连超时")
return origin_status, b'{"DemoPlugin": {"version": "1.0.0"}}'
@contextmanager
@@ -398,8 +402,8 @@ async def test_plugin_index_fallback_checks_response_before_accepting_it(
用离线响应替代同步出站流。
"""
assert raise_exception is True
raw = response_for(url)
yield _SyncStreamResponse(raw[1], status_code=raw[0]) if raw else None
status, content = response_for(url)
yield _SyncStreamResponse(content, status_code=status)
@asynccontextmanager
async def async_stream(*, url: str, raise_exception: bool):
@@ -407,8 +411,8 @@ async def test_plugin_index_fallback_checks_response_before_accepting_it(
用离线响应替代异步出站流。
"""
assert raise_exception is True
raw = response_for(url)
yield _AsyncStreamResponse(raw[1], status_code=raw[0]) if raw else None
status, content = response_for(url)
yield _AsyncStreamResponse(content, status_code=status)
monkeypatch.setattr(
plugin_client_module, "RequestUtils", Mock(return_value=SimpleNamespace(get_stream=sync_stream))
@@ -440,6 +444,11 @@ async def test_plugin_index_fallback_checks_response_before_accepting_it(
assert calls == [mirror_url]
else:
assert calls == [mirror_url, index_url]
assert any("将使用原始出口" in call.args[0] for call in debug.call_args_list)
if origin_status is None:
assert any("直连超时" in call.args[0] for call in debug.call_args_list)
warning.assert_not_called()
error.assert_not_called()
@pytest.mark.asyncio
@@ -862,7 +871,7 @@ def test_plugin_index_parse_error_does_not_log_response_payload(monkeypatch) ->
"""
messages: list[str] = []
monkeypatch.setattr(
"app.adapters.external.plugin.client.logger.warning",
"app.adapters.external.plugin.client.logger.debug",
lambda message: messages.append(message),
)
@@ -882,7 +891,7 @@ def test_plugin_index_parse_error_logs_source_without_cache_buster(monkeypatch)
"""
messages: list[str] = []
monkeypatch.setattr(
"app.adapters.external.plugin.client.logger.warning",
"app.adapters.external.plugin.client.logger.debug",
lambda message: messages.append(message),
)
@@ -907,7 +916,7 @@ def test_plugin_index_source_log_drops_credentials(monkeypatch) -> None:
"""
messages: list[str] = []
monkeypatch.setattr(
"app.adapters.external.plugin.client.logger.warning",
"app.adapters.external.plugin.client.logger.debug",
lambda message: messages.append(message),
)
@@ -934,29 +943,47 @@ def test_plugin_index_read_failure_logs_requested_url(monkeypatch) -> None:
"""
messages: list[str] = []
monkeypatch.setattr(
"app.adapters.external.plugin.client.logger.warning",
"app.adapters.external.plugin.client.logger.debug",
lambda message: messages.append(message),
)
class FakeResponse:
"""占位响应对象,实际内容由读取函数替换。"""
"""
占位响应对象,实际内容由读取函数替换。
"""
class FakeStream:
"""提供 with 语义的占位流。"""
"""
提供 with 语义的占位流。
"""
def __enter__(self):
"""
返回用于触发解析失败的占位响应。
"""
return FakeResponse()
def __exit__(self, *_args):
"""
让读取异常按原样离开上下文。
"""
return False
class FakeRequestUtils:
"""跳过真实网络请求的请求器。"""
"""
跳过真实网络请求的请求器。
"""
def __init__(self, **_kwargs):
"""
接受测试生成的出口参数。
"""
pass
def get_stream(self, **_kwargs):
"""
返回无网络依赖的响应上下文。
"""
return FakeStream()
monkeypatch.setattr(plugin_client_module, "RequestUtils", FakeRequestUtils)

View File

@@ -51,6 +51,7 @@ def _merge_catalog_plugins(higher, base, markets):
),
warning=Mock(),
error=Mock(),
info=Mock(),
)
return service.merge(higher, base, markets)