diff --git a/music_api/podcast.py b/music_api/podcast.py index 4550df9..9cf8aca 100644 --- a/music_api/podcast.py +++ b/music_api/podcast.py @@ -434,6 +434,27 @@ def get_hot_radios(cookies: dict[str, str] | None = None, return [] +_FALLDOWN_LADDER = ['hires', 'lossless', 'exhigh', 'standard'] + + +def _falldown_order(level: str) -> list[str]: + """音质降级尝试序列:只向下不向上(原实现指定 standard 会回退到更高的 exhigh)。 + + - auto/空 → 通用阶梯原序 + - 已知音质 → 该音质 + 阶梯中低于它的部分 + - 未知音质 → 该音质优先 + 通用阶梯(去重保序) + """ + level = str(level or 'auto').strip() + if not level or level == 'auto': + order = list(PodcastConstants.QUALITY_LADDER) + elif level in _FALLDOWN_LADDER: + idx = _FALLDOWN_LADDER.index(level) + order = [level, *_FALLDOWN_LADDER[idx + 1:]] + else: + order = [level, *PodcastConstants.QUALITY_LADDER] + return list(dict.fromkeys(order)) # 去重保序 + + def resolve_episode_url(song_id: Any, cookies: dict[str, str] | None = None, level: str = 'auto') -> dict[str, Any] | None: """解析单集音频直链(带音质降级) @@ -446,35 +467,13 @@ def resolve_episode_url(song_id: Any, cookies: dict[str, str] | None = None, Returns: {'url','level','type','size','br','md5'} 或 None(全部失败) """ - # 降级阶梯只向下不向上——原实现指定 standard 会回退到更高的 exhigh - _FALLDOWN_LADDER = ['hires', 'lossless', 'exhigh', 'standard'] - order: list[str] = [] - level = str(level or 'auto').strip() - if level and level != 'auto': - order.append(level) - # 追加"低于"请求音质的等级(hires > lossless > exhigh > standard) - if level in _FALLDOWN_LADDER: - idx = _FALLDOWN_LADDER.index(level) - for lv in _FALLDOWN_LADDER[idx + 1:]: - order.append(lv) - else: - # 未知等级:退到通用阶梯 - order.extend(PodcastConstants.QUALITY_LADDER) - else: - order.extend(PodcastConstants.QUALITY_LADDER) - # 去重保序 - dedup: list[str] = [] + order = _falldown_order(level) + # song_id 可能是 None/垃圾值(防御:int 失败按无音频处理,不再 TypeError 500) + try: + sid = int(str(song_id).strip()) + except (TypeError, ValueError): + return None for lv in order: - if lv not in dedup: - dedup.append(lv) - order = dedup - - for lv in order: - try: - # song_id 可能是 None/垃圾值(防御:int 失败按无音频处理,不再 TypeError 500) - sid = int(str(song_id).strip()) - except (TypeError, ValueError): - return None try: res = url_v1(sid, lv, cookies or {}) except (APIException, ValueError): diff --git a/tests/test_resolve_episode_url.py b/tests/test_resolve_episode_url.py new file mode 100644 index 0000000..9a0c7fa --- /dev/null +++ b/tests/test_resolve_episode_url.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +"""resolve_episode_url 的行为契约测试(沙箱,不触真实上游)。 + +为什么:播客单集直链解析的唯一入口(音质降级阶梯 + 尝试循环), +此前零直接测试。降级阶梯的口径是核心可观察行为: +- auto → QUALITY_LADDER 原序 +- 显式音质 → 只向下不向上(standard 绝不回退到更高的 exhigh) +- 未知音质 → 该音质优先 + 通用阶梯 +- song_id 垃圾值 → None 且不发任何请求 + +替身边界:monkeypatch ``podcast.url_v1``(模块级名字,podcast.py 从 +.compat 导入后的绑定),按 level 返回结果或抛异常,并记录调用序列。 +""" +import pytest + +from music_api import APIException +from music_api import podcast as podcast_mod +from music_api.podcast import resolve_episode_url + + +@pytest.fixture() +def url_calls(monkeypatch): + calls: list[tuple[int, str]] = [] + state: dict = {'results': {}} + + def _fake_url_v1(sid, level, cookies): + calls.append((sid, level)) + r = state['results'].get(level) + if isinstance(r, Exception): + raise r + return r + + monkeypatch.setattr(podcast_mod, 'url_v1', _fake_url_v1) + state['calls'] = calls + return state + + +def _ok(level: str = 'standard') -> dict: + return {'data': [{'url': 'https://x/1.mp3', 'level': level, 'type': 'mp3', + 'size': '123', 'br': 128000, 'md5': 'abc'}]} + + +async def test_auto_tries_quality_ladder_in_order(url_calls): + """auto:按 QUALITY_LADDER 原序尝试,全失败返回 None。""" + assert resolve_episode_url(101, {}, 'auto') is None + assert url_calls['calls'] == [(101, 'exhigh'), (101, 'standard')] + + +async def test_explicit_level_falls_down_only(url_calls): + """显式 lossless:向后降级 exhigh/standard,绝不向上尝试 hires。""" + assert resolve_episode_url(101, {}, 'lossless') is None + assert url_calls['calls'] == [(101, 'lossless'), (101, 'exhigh'), (101, 'standard')] + + +async def test_standard_never_falls_up(url_calls): + """显式 standard:只试一次(历史坑:原实现会回退到更高的 exhigh)。""" + assert resolve_episode_url(101, {}, 'standard') is None + assert url_calls['calls'] == [(101, 'standard')] + + +async def test_unknown_level_prepends_generic_ladder(url_calls): + """未知音质:先试该音质,再退通用阶梯(去重保序)。""" + assert resolve_episode_url(101, {}, 'sky') is None + assert url_calls['calls'] == [(101, 'sky'), (101, 'exhigh'), (101, 'standard')] + + +async def test_first_hit_returns_mapped_result(url_calls): + url_calls['results']['exhigh'] = _ok('hires') + out = resolve_episode_url(101, {}, 'auto') + assert out == {'url': 'https://x/1.mp3', 'level': 'hires', 'type': 'mp3', + 'size': 123, 'br': 128000, 'md5': 'abc', 'requested_level': 'exhigh'} + + +async def test_level_defaults_to_requested_when_missing(url_calls): + url_calls['results']['exhigh'] = {'data': [{'url': 'https://x/1.mp3'}]} + out = resolve_episode_url(101, {}, 'auto') + assert out is not None + assert out['level'] == 'exhigh' + assert out['type'] == 'mp3' + assert out['md5'] == '' + assert out['size'] is None + + +async def test_api_exception_tries_next_level(url_calls): + url_calls['results']['exhigh'] = APIException('无版权') + url_calls['results']['standard'] = _ok() + out = resolve_episode_url(101, {}, 'auto') + assert out is not None + assert out['requested_level'] == 'standard' + assert url_calls['calls'] == [(101, 'exhigh'), (101, 'standard')] + + +async def test_missing_url_tries_next_level(url_calls): + """data[0] 无 url:视同失败,继续降级。""" + url_calls['results']['exhigh'] = {'data': [{'url': None}]} + url_calls['results']['standard'] = _ok() + out = resolve_episode_url(101, {}, 'auto') + assert out is not None + assert out['requested_level'] == 'standard' + + +async def test_empty_data_tries_next_level(url_calls): + url_calls['results']['exhigh'] = None # res 为 None → data 为 [] + url_calls['results']['standard'] = _ok() + out = resolve_episode_url(101, {}, 'auto') + assert out is not None + assert out['requested_level'] == 'standard' + + +async def test_bad_song_id_returns_none_without_requests(url_calls): + """song_id 垃圾值:None,且不发任何请求(防御原 TypeError 500)。""" + for bad in (None, 'abc', ''): + assert resolve_episode_url(bad, {}, 'auto') is None + assert url_calls['calls'] == [] + + +async def test_numeric_string_song_id_accepted(url_calls): + url_calls['results']['exhigh'] = _ok() + out = resolve_episode_url(' 101 ', {}, 'auto') + assert out is not None + assert url_calls['calls'][0] == (101, 'exhigh')