mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-30 07:56:21 +08:00
fix(subscribe): preserve media query failures across HTTP and servers
This commit is contained in:
@@ -158,11 +158,10 @@ class DownloadExistenceOwner(_DownloadOwnerBase):
|
||||
|
||||
:param mediainfo: 本次查询的媒体信息
|
||||
:param query: 本次查询的媒体服务器参数
|
||||
:param raise_on_query_failure: 剧集查询失败且没有服务器确认存在时抛
|
||||
MediaServerQueryError;默认 False 时查询失败按未找到处理
|
||||
:param raise_on_query_failure: 任一服务器剧集查询失败时抛 MediaServerQueryError,
|
||||
避免用其他服务器的部分集数推断缺失;默认 False 时保留已确认结果
|
||||
:return: 已确认存在的媒体信息;没有服务器确认存在时为 None
|
||||
:raises MediaServerQueryError: 剧集查询失败且 raise_on_query_failure 为 True,
|
||||
且没有服务器确认媒体存在时
|
||||
:raises MediaServerQueryError: 任一剧集查询失败且 raise_on_query_failure 为 True
|
||||
"""
|
||||
server_names = [str(config.name) for config in get_mediaserver_configs() if config.name]
|
||||
if not server_names:
|
||||
@@ -185,7 +184,7 @@ class DownloadExistenceOwner(_DownloadOwnerBase):
|
||||
raise_on_query_failure=raise_on_query_failure,
|
||||
)
|
||||
except MediaServerQueryError:
|
||||
# 单台服务器失败不阻断其余服务器;全部失败才在循环后统一抛异常。
|
||||
# 收集失败并继续查询其余服务器;严格口径不能据部分结果推断缺集。
|
||||
failed_servers.append(server)
|
||||
continue
|
||||
if exists:
|
||||
@@ -194,14 +193,14 @@ class DownloadExistenceOwner(_DownloadOwnerBase):
|
||||
combined = combined or exists
|
||||
for season, episodes in (exists.seasons or {}).items():
|
||||
seasons.setdefault(season, set()).update(episodes)
|
||||
if combined:
|
||||
return combined.model_copy(update={
|
||||
"seasons": {season: sorted(episodes) for season, episodes in seasons.items()},
|
||||
})
|
||||
if failed_servers and raise_on_query_failure:
|
||||
raise MediaServerQueryError(
|
||||
f"媒体库查询失败,未能确认 {mediainfo.title_year} 是否已入库:{', '.join(failed_servers)}"
|
||||
)
|
||||
if combined:
|
||||
return combined.model_copy(update={
|
||||
"seasons": {season: sorted(episodes) for season, episodes in seasons.items()},
|
||||
})
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -27,6 +27,32 @@ _EMBY_ITEMS_PAGE_SIZE = 200
|
||||
_EMBY_EPISODE_RANGE_MAX_SPAN = 1000
|
||||
|
||||
|
||||
def read_emby_query_items(
|
||||
request: "RequestUtils", url: str, params: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
读取存在性查询的条目列表,区分成功空列表与不可确认的响应。
|
||||
|
||||
:param request: 保留当前媒体服务器认证配置的 HTTP 工具
|
||||
:param url: 标题搜索或分集查询地址
|
||||
:param params: 当前请求的查询条件与内容投影
|
||||
:return: 已验证的原始条目列表,成功查询无条目时为空列表
|
||||
:raises MediaServerQueryError: 无响应、非 200 状态或条目结构无效
|
||||
"""
|
||||
response = request.get_res(url, params)
|
||||
if response is None:
|
||||
raise MediaServerQueryError("媒体库查询失败:未收到响应")
|
||||
try:
|
||||
if response.status_code != 200:
|
||||
raise MediaServerQueryError(f"媒体库查询失败:HTTP {response.status_code}")
|
||||
items = response.json().get("Items")
|
||||
if not isinstance(items, list) or any(not isinstance(item, dict) for item in items):
|
||||
raise MediaServerQueryError("媒体库查询失败:条目列表格式无效")
|
||||
return items
|
||||
finally:
|
||||
response.close()
|
||||
|
||||
|
||||
def _read_emby_item_page(
|
||||
request: "RequestUtils",
|
||||
url: str,
|
||||
|
||||
@@ -13,7 +13,12 @@ from requests import Response
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.application.mediaserver import MediaServerIdentityHelper, format_emby_family_item
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.modules._base.mediaserver import emby_episode_numbers, emby_query_params, iter_emby_items
|
||||
from app.modules._base.mediaserver import (
|
||||
emby_episode_numbers,
|
||||
emby_query_params,
|
||||
iter_emby_items,
|
||||
read_emby_query_items,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
@@ -452,15 +457,11 @@ class Emby:
|
||||
}
|
||||
try:
|
||||
params.update(emby_query_params(query))
|
||||
res = RequestUtils().get_res(url, params)
|
||||
if res:
|
||||
res_items = res.json().get("Items")
|
||||
if res_items:
|
||||
for res_item in res_items:
|
||||
if res_item.get("Name") == name and (
|
||||
not year or str(res_item.get("ProductionYear")) == str(year)
|
||||
):
|
||||
return _optional_text(res_item.get("Id"))
|
||||
for res_item in read_emby_query_items(RequestUtils(), url, params):
|
||||
if res_item.get("Name") == name and (
|
||||
not year or str(res_item.get("ProductionYear")) == str(year)
|
||||
):
|
||||
return _optional_text(res_item.get("Id"))
|
||||
except Exception as e:
|
||||
logger.error("连接Items出错:" + str(e))
|
||||
return None
|
||||
@@ -666,8 +667,8 @@ class Emby:
|
||||
:param media_id: 对应来源的媒体标识
|
||||
:param season: 目标季号;None 表示查询全部季
|
||||
:param query: 可选查询内容投影,省略时保留原有请求和返回内容
|
||||
:return: 电视剧条目标识与“季号到集号列表”映射;配置缺失或异常返回两项 None,
|
||||
未找到、身份不兼容或响应无可用数据时返回 None 和空映射
|
||||
:return: 电视剧条目标识与季集映射;配置、请求或身份校验不可用时返回两项 None,
|
||||
仅确认未找到、身份冲突或成功查询无分集时返回空映射
|
||||
"""
|
||||
if not self._host or not self._apikey:
|
||||
return None, None
|
||||
@@ -696,7 +697,7 @@ class Emby:
|
||||
**({"query": query.with_fields(MediaServerField.IDENTITY)} if query is not None else {}),
|
||||
)
|
||||
if not item_info:
|
||||
return None, {}
|
||||
return None, None
|
||||
if not MediaServerIdentityHelper.is_compatible(item_info, media_source, media_id):
|
||||
return None, {}
|
||||
if season is None:
|
||||
@@ -709,28 +710,23 @@ class Emby:
|
||||
MediaServerQueryOptions(fields=frozenset()) if query is not None and query.fields is not None else None
|
||||
)
|
||||
)
|
||||
res_json = RequestUtils().get_res(url, params)
|
||||
if res_json:
|
||||
tv_item = res_json.json()
|
||||
res_items = tv_item.get("Items")
|
||||
season_episodes: dict[int, list[int]] = {}
|
||||
for res_item in res_items:
|
||||
season_index = res_item.get("ParentIndexNumber")
|
||||
if season_index is None:
|
||||
continue
|
||||
if season is not None and season != season_index:
|
||||
continue
|
||||
episode_index = res_item.get("IndexNumber")
|
||||
if episode_index is None:
|
||||
continue
|
||||
if season_index not in season_episodes:
|
||||
season_episodes[season_index] = []
|
||||
season_episodes[season_index].extend(emby_episode_numbers(res_item))
|
||||
return item_id, season_episodes
|
||||
season_episodes: dict[int, list[int]] = {}
|
||||
for res_item in read_emby_query_items(RequestUtils(), url, params):
|
||||
season_index = res_item.get("ParentIndexNumber")
|
||||
if season_index is None:
|
||||
continue
|
||||
if season is not None and season != season_index:
|
||||
continue
|
||||
episode_index = res_item.get("IndexNumber")
|
||||
if episode_index is None:
|
||||
continue
|
||||
if season_index not in season_episodes:
|
||||
season_episodes[season_index] = []
|
||||
season_episodes[season_index].extend(emby_episode_numbers(res_item))
|
||||
return item_id, season_episodes
|
||||
except Exception as e:
|
||||
logger.error("连接Shows/Id/Episodes出错:" + str(e))
|
||||
return None, None
|
||||
return None, {}
|
||||
|
||||
def get_season_episode_ids(
|
||||
self, item_id: str, season: int, *, query: Optional[MediaServerQueryOptions] = None
|
||||
|
||||
@@ -11,7 +11,12 @@ from requests import Response
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.application.mediaserver import MediaServerIdentityHelper, format_emby_family_item
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.modules._base.mediaserver import emby_episode_numbers, emby_query_params, iter_emby_items
|
||||
from app.modules._base.mediaserver import (
|
||||
emby_episode_numbers,
|
||||
emby_query_params,
|
||||
iter_emby_items,
|
||||
read_emby_query_items,
|
||||
)
|
||||
from app.runtime.cache import MemoryBackend
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
@@ -519,7 +524,10 @@ class Jellyfin:
|
||||
"""
|
||||
根据名称查询Jellyfin中剧集的SeriesId。
|
||||
|
||||
:param name: 需要精确匹配的剧名
|
||||
:param year: 可选首播年份
|
||||
:param query: 可选查询内容投影,省略时保留原有请求和返回内容
|
||||
:return: 匹配标识;确认无匹配时为空字符串,请求失败或响应无效时为 None
|
||||
"""
|
||||
if not self._host or not self._apikey or not self.user:
|
||||
return None
|
||||
@@ -533,15 +541,11 @@ class Jellyfin:
|
||||
}
|
||||
try:
|
||||
params.update(emby_query_params(query))
|
||||
res = self._request().get_res(url, params)
|
||||
if res:
|
||||
res_items = res.json().get("Items")
|
||||
if res_items:
|
||||
for res_item in res_items:
|
||||
if res_item.get("Name") == name and (
|
||||
not year or str(res_item.get("ProductionYear")) == str(year)
|
||||
):
|
||||
return _optional_text(res_item.get("Id"))
|
||||
for res_item in read_emby_query_items(self._request(), url, params):
|
||||
if res_item.get("Name") == name and (
|
||||
not year or str(res_item.get("ProductionYear")) == str(year)
|
||||
):
|
||||
return _optional_text(res_item.get("Id"))
|
||||
except Exception as e:
|
||||
logger.error("连接Items出错:" + str(e))
|
||||
return None
|
||||
@@ -744,8 +748,8 @@ class Jellyfin:
|
||||
:param media_id: 对应来源的媒体标识
|
||||
:param season: 目标季号;None 表示查询全部季
|
||||
:param query: 可选查询内容投影,省略时保留原有请求和返回内容
|
||||
:return: 电视剧条目标识与“季号到集号列表”映射;配置缺失或异常返回两项 None,
|
||||
未找到、身份不兼容或响应无可用数据时返回 None 和空映射
|
||||
:return: 电视剧条目标识与季集映射;配置、请求或身份校验不可用时返回两项 None,
|
||||
仅确认未找到、身份冲突或成功查询无分集时返回空映射
|
||||
"""
|
||||
if not self._host or not self._apikey or not self.user:
|
||||
return None, None
|
||||
@@ -778,7 +782,7 @@ class Jellyfin:
|
||||
**({"query": query.with_fields(MediaServerField.IDENTITY)} if query is not None else {}),
|
||||
)
|
||||
if not item_info:
|
||||
return None, {}
|
||||
return None, None
|
||||
if not MediaServerIdentityHelper.is_compatible(item_info, media_source, media_id):
|
||||
return None, {}
|
||||
if season is None:
|
||||
@@ -791,28 +795,23 @@ class Jellyfin:
|
||||
MediaServerQueryOptions(fields=frozenset()) if query is not None and query.fields is not None else None
|
||||
)
|
||||
)
|
||||
res_json = self._request().get_res(url, params)
|
||||
if res_json:
|
||||
tv_info = res_json.json()
|
||||
res_items = tv_info.get("Items")
|
||||
season_episodes: dict[int, list[int]] = {}
|
||||
for res_item in res_items:
|
||||
season_index = res_item.get("ParentIndexNumber")
|
||||
if season_index is None:
|
||||
continue
|
||||
if season is not None and season != season_index:
|
||||
continue
|
||||
episode_index = res_item.get("IndexNumber")
|
||||
if episode_index is None:
|
||||
continue
|
||||
if not season_episodes.get(season_index):
|
||||
season_episodes[season_index] = []
|
||||
season_episodes[season_index].extend(emby_episode_numbers(res_item))
|
||||
return item_id, season_episodes
|
||||
season_episodes: dict[int, list[int]] = {}
|
||||
for res_item in read_emby_query_items(self._request(), url, params):
|
||||
season_index = res_item.get("ParentIndexNumber")
|
||||
if season_index is None:
|
||||
continue
|
||||
if season is not None and season != season_index:
|
||||
continue
|
||||
episode_index = res_item.get("IndexNumber")
|
||||
if episode_index is None:
|
||||
continue
|
||||
if not season_episodes.get(season_index):
|
||||
season_episodes[season_index] = []
|
||||
season_episodes[season_index].extend(emby_episode_numbers(res_item))
|
||||
return item_id, season_episodes
|
||||
except Exception as e:
|
||||
logger.error("连接Shows/Id/Episodes出错:" + str(e))
|
||||
return None, None
|
||||
return None, {}
|
||||
|
||||
def get_season_episode_ids(
|
||||
self, item_id: str, season: int, *, query: Optional[MediaServerQueryOptions] = None
|
||||
|
||||
@@ -94,6 +94,11 @@ Do not raise `HTTPException` in chain or module code. Chains and modules return
|
||||
| Chain | Log the error, return `None` or an appropriate domain object with failure indication |
|
||||
| Endpoint | Translate `None` or failure result into a `Response(success=False, ...)` or `HTTPException` |
|
||||
|
||||
媒体库存在性查询使用严格口径时,模块通过 `MediaServerQueryError` 传播无法确认的查询结果,
|
||||
订阅入口跳过本轮并保留缺集进度。Emby/Jellyfin 的标题和分集查询仅将 HTTP 200 且
|
||||
`Items` 为有效条目列表的空结果视为“未找到”;超时、非 200、无效响应及无法确认的条目身份
|
||||
必须保留失败状态。多服务器查询中任一服务器失败时,不能用其他服务器的部分集数推断缺失。
|
||||
|
||||
```python
|
||||
def test(self) -> Optional[Tuple[bool, str]]:
|
||||
"""
|
||||
|
||||
@@ -104,6 +104,11 @@ MoviePilot 当前以媒体类型和洗版方式组合出常用订阅模式。普
|
||||
|
||||
### 事实写入
|
||||
|
||||
普通电视剧订阅计算缺集时使用严格媒体库查询。Emby/Jellyfin 标题搜索、条目身份或分集读取
|
||||
失败时,本轮不更新缺集、不继续补下;服务器恢复后由后续轮次重新查询。配置了多台服务器时,
|
||||
任一服务器查询失败都保留未知状态,不能用另一台服务器的部分集数断言其余集数不存在。
|
||||
成功确认未找到目标仍按正常缺失处理。媒体库查询只派生进度,不自动把扫描到的集数写入 `note`。
|
||||
|
||||
- 公共创建与普通订阅编辑只负责目标和配置变更,不直接维护下载事实和进度摘要;Agent 或维护工具需要修正运行事实时,应使用受控的内部工具或领域入口。
|
||||
- 主程序下载链路产生的电视剧下载必须同时维护 `note` 和 `episode_priority`。
|
||||
- backfill 入口只接收调用方确认的外部存在事实,不主动扫描媒体库。
|
||||
|
||||
@@ -158,6 +158,14 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)):
|
||||
|
||||
> 注意:识别这类端到端流程往往不止一个外部出口。例如 TMDB 识别除了目录请求,链路层还会向 MP 服务器上报/查询「共享识别 API」——这类旁路出口必须一并打桩。用下文的 socket 探针确认确实零出站。
|
||||
|
||||
### 媒体库查询失败与订阅缺集
|
||||
|
||||
`tests/test_mediaserver_existence_failure.py` 连接真实 Emby/Jellyfin 客户端、模块调度器、
|
||||
缺集计算和订阅进度入口,仅替换 HTTP 与持久化出口。测试覆盖标题搜索、缓存回查、详情及
|
||||
分集接口的无响应、HTTP 错误和无效条目结构,以及空库、服务恢复和多服务器部分失败。
|
||||
失败时不写缺集进度、不完成订阅;媒体库恢复后按实际已有季集重新计算,保留订阅下载事实。
|
||||
这些离线测试不代表真实媒体服务器或报告者 Docker 实例验收。
|
||||
|
||||
### 飞书长会话流式卡片回归
|
||||
|
||||
`tests/test_feishu.py` 在 CardKit API 边界模拟 `300309` / `200850`:重开同一卡片的
|
||||
|
||||
@@ -84,7 +84,7 @@
|
||||
"app/domain/projection/anilist.py:project": 17,
|
||||
"app/domain/projection/douban.py:project": 25,
|
||||
"app/modules/discord/discord.py:Discord._build_embed": 26,
|
||||
"app/modules/emby/emby.py:Emby.get_tv_episodes": 18,
|
||||
"app/modules/emby/emby.py:Emby.get_tv_episodes": 17,
|
||||
"app/modules/emby/emby.py:Emby.get_webhook_message": 18,
|
||||
"app/modules/filemanager/storages/alipan.py:AliPan.upload": 16,
|
||||
"app/modules/filemanager/storages/u115.py:U115Pan.upload": 32,
|
||||
@@ -93,7 +93,7 @@
|
||||
"app/modules/filter/__init__.py:FilterModule.__match_rule": 24,
|
||||
"app/modules/imdb/__init__.py:ImdbModule._to_media_info": 17,
|
||||
"app/modules/indexer/spider/__init__.py:SiteSpider.__get_search_url": 24,
|
||||
"app/modules/jellyfin/jellyfin.py:Jellyfin.get_tv_episodes": 18,
|
||||
"app/modules/jellyfin/jellyfin.py:Jellyfin.get_tv_episodes": 17,
|
||||
"app/modules/qbittorrent/__init__.py:QbittorrentModule.download": 19,
|
||||
"app/modules/qbittorrent/__init__.py:QbittorrentModule.list_torrents": 20,
|
||||
"app/modules/qqbot/gateway.py:run_gateway": 42,
|
||||
|
||||
198
tests/test_mediaserver_existence_failure.py
Normal file
198
tests/test_mediaserver_existence_failure.py
Normal file
@@ -0,0 +1,198 @@
|
||||
"""
|
||||
媒体库读取失败不得退化为整季缺失,订阅进度与下载事实必须保留。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from requests import Response
|
||||
|
||||
from app.application.mediaserver import MediaServerQueryError
|
||||
from app.application.subscription.contract import SubscriptionSnapshot
|
||||
from app.chain.download.existence import DownloadExistenceOwner
|
||||
from app.chain.subscribe.facade import SubscribeChain
|
||||
from app.domain.context import MediaInfo
|
||||
from app.domain.meta.metavideo import MetaVideo
|
||||
from app.modules.emby import EmbyModule
|
||||
from app.modules.emby.emby import Emby
|
||||
from app.modules.jellyfin import JellyfinModule
|
||||
from app.modules.jellyfin.jellyfin import Jellyfin
|
||||
from app.runtime.extensions.module.dispatcher import ModuleInvocationDispatcher
|
||||
from app.schemas.mediaserver import ExistMediaInfo
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
|
||||
def _response(payload: object, status: int = 200) -> Response:
|
||||
"""
|
||||
构造保留真实 HTTP 状态与真假语义的离线响应。
|
||||
"""
|
||||
response = Response()
|
||||
response.status_code = status
|
||||
response._content = b""
|
||||
response._content_consumed = True
|
||||
response.json = Mock(return_value=payload)
|
||||
return response
|
||||
|
||||
|
||||
@pytest.fixture(params=[(Emby, EmbyModule), (Jellyfin, JellyfinModule)], ids=["emby", "jellyfin"])
|
||||
def library_query(request, monkeypatch):
|
||||
"""
|
||||
连接真实客户端、模块调度器与缺集链,只替换 HTTP 和持久化出口。
|
||||
"""
|
||||
client_type, module_type = request.param
|
||||
client = client_type.__new__(client_type)
|
||||
client._host, client._apikey, client.user = "https://media.invalid/", "synthetic-key", "user"
|
||||
client._sync_libraries = []
|
||||
transport = Mock()
|
||||
monkeypatch.setattr(f"{client_type.__module__}.RequestUtils", Mock(return_value=transport))
|
||||
module = module_type.__new__(module_type)
|
||||
module._instances = {"main": client}
|
||||
dispatcher = ModuleInvocationDispatcher(
|
||||
module_catalog=Mock(get_running_modules=Mock(return_value=[module])),
|
||||
plugin_catalog=Mock(get_plugin_modules=Mock(return_value={})),
|
||||
plugin_error_handler=Mock(), system_error_handler=Mock(), rate_limit_handler=Mock(),
|
||||
)
|
||||
owner = DownloadExistenceOwner.__new__(DownloadExistenceOwner)
|
||||
owner._module_dispatcher = dispatcher
|
||||
owner.media_server_repository = Mock(get_item_id=Mock(return_value="cached-series"))
|
||||
monkeypatch.setattr("app.chain.download.existence.get_mediaserver_configs",
|
||||
lambda: [SimpleNamespace(name="main")])
|
||||
media = MediaInfo(type=MediaType.TV, title="示例剧集", year="2023",
|
||||
media_source=MediaSource.TMDB, media_id="123", seasons={1: list(range(1, 201))})
|
||||
return owner, transport, media
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", ["search", "uncached-search", "detail", "episodes"])
|
||||
@pytest.mark.parametrize("failure", ["timeout", "http", "malformed", "wrong-items"])
|
||||
def test_failed_library_query_never_returns_whole_season_missing(library_query, phase, failure):
|
||||
"""
|
||||
标题搜索、详情或分集查询失败都必须中止缺集推断,不能把已有集数变成缺失。
|
||||
"""
|
||||
owner, transport, media = library_query
|
||||
failed = {"timeout": None, "http": _response({"Items": []}, 503),
|
||||
"malformed": _response({}), "wrong-items": _response({"Items": {}})}[failure]
|
||||
series = {"Id": "series", "Type": "Series", "Name": media.title, "ProductionYear": 2023,
|
||||
"ProviderIds": {"Tmdb": "123"}}
|
||||
if phase == "uncached-search":
|
||||
owner.media_server_repository.get_item_id.return_value = None
|
||||
transport.get_res.return_value = failed
|
||||
elif phase == "search":
|
||||
transport.get_res.side_effect = [_response({"Items": []}), failed]
|
||||
elif phase == "detail":
|
||||
transport.get_res.side_effect = [failed, _response({"Items": [series]}), failed]
|
||||
else:
|
||||
transport.get_res.side_effect = [_response({"Items": [series]}), failed]
|
||||
previous = {"tmdb:other": {}}
|
||||
|
||||
with pytest.raises(MediaServerQueryError, match="媒体库.*查询失败"):
|
||||
owner.get_no_exists_info(MetaVideo("示例剧集 S01"), media, no_exists=previous, raise_on_query_failure=True)
|
||||
|
||||
assert previous == {"tmdb:other": {}}
|
||||
|
||||
|
||||
def test_confirmed_absence_still_produces_missing_season(library_query):
|
||||
"""
|
||||
成功查询确认缓存条目与标题均不存在时,继续允许整季补缺。
|
||||
"""
|
||||
owner, transport, media = library_query
|
||||
transport.get_res.return_value = _response({"Items": []})
|
||||
|
||||
exists, missing = owner.get_no_exists_info(MetaVideo("示例剧集 S01"), media, raise_on_query_failure=True)
|
||||
|
||||
assert exists is False
|
||||
assert missing["tmdb:123"][1].episodes == []
|
||||
assert missing["tmdb:123"][1].total_episode == 200
|
||||
|
||||
|
||||
def test_unconfigured_client_cannot_confirm_missing_episodes(library_query):
|
||||
"""
|
||||
启动时连接未就绪或凭据配置缺失,不能放行电视剧补缺。
|
||||
"""
|
||||
owner, _, media = library_query
|
||||
module = owner._module_dispatcher._module_catalog.get_running_modules.return_value[0]
|
||||
module._instances["main"]._host = None
|
||||
|
||||
with pytest.raises(MediaServerQueryError):
|
||||
owner.get_no_exists_info(MetaVideo("示例剧集 S01"), media, raise_on_query_failure=True)
|
||||
|
||||
|
||||
def test_default_existence_call_keeps_error_isolation(library_query):
|
||||
"""
|
||||
未开启严格模式的既有存在性调用保留异常隔离,严格查询则向调用方传递失败。
|
||||
"""
|
||||
owner, transport, media = library_query
|
||||
transport.get_res.return_value = None
|
||||
|
||||
assert owner.media_exists(media, server="main") is None
|
||||
with pytest.raises(MediaServerQueryError):
|
||||
owner.media_exists(media, server="main", raise_on_query_failure=True)
|
||||
|
||||
|
||||
def test_default_server_fallback_also_propagates_query_failures(library_query, monkeypatch):
|
||||
"""
|
||||
不限定媒体服务器的兼容路径同样必须保留查询失败,不能退化成整季缺失。
|
||||
"""
|
||||
owner, transport, media = library_query
|
||||
monkeypatch.setattr("app.chain.download.existence.get_mediaserver_configs", lambda: [])
|
||||
transport.get_res.return_value = None
|
||||
|
||||
with pytest.raises(MediaServerQueryError):
|
||||
owner.get_no_exists_info(MetaVideo("示例剧集 S01"), media, raise_on_query_failure=True)
|
||||
|
||||
|
||||
def test_library_recovery_reuses_real_episodes_without_mutating_download_note(library_query, monkeypatch):
|
||||
"""
|
||||
媒体库故障中断对账,恢复后仍以已有 167 集计算缺集,不改写订阅下载事实。
|
||||
"""
|
||||
owner, transport, media = library_query
|
||||
chain = SubscribeChain.__new__(SubscribeChain)
|
||||
chain._SubscribeChain__refresh_total_episode_before_completion = Mock(side_effect=lambda **kwargs: kwargs["subscribe"])
|
||||
chain._SubscribeChain__refresh_subscribe_progress_with_no_exists = Mock()
|
||||
chain.finish_subscribe_or_not = Mock()
|
||||
monkeypatch.setattr("app.chain.subscribe.refresh.DownloadChain", lambda: owner)
|
||||
subscribe = SubscriptionSnapshot(
|
||||
id=7444,
|
||||
type=MediaType.TV.value, name=media.title, year="2023", media_source=MediaSource.TMDB,
|
||||
media_id="123", season=1, best_version=0, start_episode=1, total_episode=200,
|
||||
manual_total_episode=0, lack_episode=33, note=list(range(157, 168)),
|
||||
)
|
||||
transport.get_res.return_value = None
|
||||
meta = MetaVideo("示例剧集 S01")
|
||||
|
||||
with pytest.raises(MediaServerQueryError, match="媒体库.*查询失败"):
|
||||
chain.check_and_handle_existing_media(subscribe, meta, media, "tmdb:123")
|
||||
|
||||
chain._SubscribeChain__refresh_subscribe_progress_with_no_exists.assert_not_called()
|
||||
chain.finish_subscribe_or_not.assert_not_called()
|
||||
assert subscribe.lack_episode == 33
|
||||
assert subscribe.note == list(range(157, 168))
|
||||
|
||||
transport.get_res.side_effect = [
|
||||
_response({"Items": [{"Id": "series", "Type": "Series", "Name": media.title,
|
||||
"ProviderIds": {"Tmdb": "123"}}]}),
|
||||
_response({"Items": [{"ParentIndexNumber": 1, "IndexNumber": ep} for ep in range(1, 168)]}),
|
||||
]
|
||||
exists, missing = chain.check_and_handle_existing_media(subscribe, meta, media, "tmdb:123")
|
||||
|
||||
assert exists is False
|
||||
assert missing["tmdb:123"][1].episodes == list(range(168, 201))
|
||||
chain._SubscribeChain__refresh_subscribe_progress_with_no_exists.assert_called_once()
|
||||
assert subscribe.note == list(range(157, 168))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failed_first", [False, True])
|
||||
def test_failed_server_cannot_be_hidden_by_another_servers_episodes(library_query, monkeypatch, failed_first):
|
||||
"""
|
||||
任一服务器查询失败时,不得用其他服务器的部分集数做缺集或完成对账。
|
||||
"""
|
||||
owner, _, media = library_query
|
||||
monkeypatch.setattr("app.chain.download.existence.get_mediaserver_configs",
|
||||
lambda: [SimpleNamespace(name="main"), SimpleNamespace(name="other")])
|
||||
results = [ExistMediaInfo(type=MediaType.TV, seasons={1: [167]}), MediaServerQueryError("查询失败")]
|
||||
owner.media_exists = Mock(side_effect=results[::-1] if failed_first else results)
|
||||
|
||||
with pytest.raises(MediaServerQueryError):
|
||||
owner.get_no_exists_info(MetaVideo("示例剧集 S01"), media, raise_on_query_failure=True)
|
||||
|
||||
assert all(call.kwargs["raise_on_query_failure"] for call in owner.media_exists.call_args_list)
|
||||
@@ -26,6 +26,7 @@ class _FakeResponse:
|
||||
保存模拟接口的响应内容与状态,避免实际网络请求。
|
||||
"""
|
||||
self._payload = payload
|
||||
self.status_code = 200
|
||||
|
||||
def json(self):
|
||||
"""
|
||||
@@ -33,6 +34,11 @@ class _FakeResponse:
|
||||
"""
|
||||
return self._payload
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
保留响应释放接缝,测试替身不持有网络资源。
|
||||
"""
|
||||
|
||||
|
||||
def _build_plex():
|
||||
"""
|
||||
|
||||
@@ -254,11 +254,11 @@ def test_server_cache_raises_when_all_servers_fail(monkeypatch: pytest.MonkeyPat
|
||||
assert isinstance(excinfo.value, _query_error_type())
|
||||
|
||||
|
||||
def test_server_cache_returns_confirmed_episodes_when_one_server_fails(
|
||||
def test_lenient_server_cache_returns_confirmed_episodes_when_one_server_fails(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
一台服务器失败、另一台确认存在时,应合并已确认的集,不抛异常。
|
||||
宽松查询在一台服务器失败时仍返回其他服务器已确认的集,保留既有调用语义。
|
||||
"""
|
||||
owner = _existence_owner()
|
||||
monkeypatch.setattr(
|
||||
@@ -280,7 +280,7 @@ def test_server_cache_returns_confirmed_episodes_when_one_server_fails(
|
||||
|
||||
owner.media_exists = Mock(side_effect=_media_exists) # type: ignore[method-assign]
|
||||
|
||||
result = owner._media_exists_with_server_cache(_media_info(), {}, raise_on_query_failure=True)
|
||||
result = owner._media_exists_with_server_cache(_media_info(), {})
|
||||
|
||||
assert result is not None
|
||||
assert result.seasons == {1: list(range(1, 168))}
|
||||
|
||||
Reference in New Issue
Block a user