Netease / test_mv_native.py
13LSR
add mv jeixi
3b08e6e
Raw History Blame Contribute Delete
12 kB
"""基于原生架构的网易云MV功能测试脚本
测试mv_api_native.py和mv_downloader_native.py的功能
包括API调用、下载功能、错误处理等测试
"""
import asyncio
import json
import time
from pathlib import Path
# 导入MV相关模块
from mv_api_native import (
NeteaseNativeMVAPI, MVInfo, MVUrlInfo, MVQuality,
get_mv_detail_native, get_mv_url_native, search_mv_native
)
from mv_downloader_native import (
MVDownloaderNative, DownloadTask, DownloadProgress,
download_mv_simple, download_mv_sync
)
def test_mv_search():
"""测试MV搜索功能"""
print("=" * 50)
print("测试MV搜索功能")
print("=" * 50)
try:
api = NeteaseNativeMVAPI()
results = api.search_mv("周杰伦", limit=5)
print(f"搜索结果: 找到 {len(results)} 个MV")
for i, mv in enumerate(results, 1):
print(f"{i}. {mv['artistName']} - {mv['name']} (ID: {mv['id']})")
print(f" 播放次数: {mv['playCount']}, 时长: {mv['duration']}ms")
print(f" 封面: {mv['cover']}")
print()
return results[0] if results else None
except Exception as e:
print(f"MV搜索测试失败: {e}")
return None
def test_mv_detail(mv_id):
"""测试MV详情获取"""
print("=" * 50)
print("测试MV详情获取")
print("=" * 50)
try:
api = NeteaseNativeMVAPI()
mv_info = api.get_mv_detail(mv_id)
print(f"MV详情:")
print(f"ID: {mv_info.id}")
print(f"名称: {mv_info.name}")
print(f"艺术家: {mv_info.artist} (ID: {mv_info.artist_id})")
print(f"时长: {mv_info.duration}ms")
print(f"发布时间: {mv_info.publish_time}")
print(f"播放次数: {mv_info.play_count}")
print(f"点赞数: {mv_info.like_count}")
print(f"分享数: {mv_info.share_count}")
print(f"评论数: {mv_info.comment_count}")
print(f"封面: {mv_info.cover_url}")
print(f"描述: {mv_info.description[:100]}..." if mv_info.description else "无描述")
print(f"标签: {mv_info.tags}")
print()
return mv_info
except Exception as e:
print(f"MV详情获取测试失败: {e}")
return None
def test_mv_url(mv_id):
"""测试MV播放链接获取"""
print("=" * 50)
print("测试MV播放链接获取")
print("=" * 50)
try:
api = NeteaseNativeMVAPI()
url_infos = api.get_mv_url(mv_id)
print(f"找到 {len(url_infos)} 个播放链接:")
for url_info in url_infos:
print(f"画质: {url_info.quality}P")
print(f"链接: {url_info.url[:80]}...")
print(f"大小: {url_info.size / (1024*1024):.2f} MB")
print(f"码率: {url_info.bitrate}")
print()
return url_infos[0] if url_infos else None
except Exception as e:
print(f"MV播放链接获取测试失败: {e}")
return None
def test_mv_comments(mv_id):
"""测试MV评论获取"""
print("=" * 50)
print("测试MV评论获取")
print("=" * 50)
try:
api = NeteaseNativeMVAPI()
comments_data = api.get_mv_comments(mv_id, limit=3)
print(f"评论总数: {comments_data.get('total', 0)}")
# 热门评论
hot_comments = comments_data.get('hotComments', [])
if hot_comments:
print(f"热门评论 ({len(hot_comments)} 条):")
for i, comment in enumerate(hot_comments[:2], 1):
user = comment.get('user', {})
print(f"{i}. {user.get('nickname', '匿名')}: {comment.get('content', '')[:50]}...")
print(f" 点赞数: {comment.get('likedCount', 0)}")
print()
# 普通评论
comments = comments_data.get('comments', [])
if comments:
print(f"最新评论 ({len(comments)} 条):")
for i, comment in enumerate(comments[:2], 1):
user = comment.get('user', {})
print(f"{i}. {user.get('nickname', '匿名')}: {comment.get('content', '')[:50]}...")
print(f" 点赞数: {comment.get('likedCount', 0)}")
print()
return True
except Exception as e:
print(f"MV评论获取测试失败: {e}")
return False
async def test_mv_download_async(mv_id, quality="720"):
"""测试异步MV下载"""
print("=" * 50)
print("测试异步MV下载")
print("=" * 50)
def progress_callback(progress: DownloadProgress):
"""进度回调函数"""
print(f"下载进度: {progress.progress:.1f}% "
f"({progress.downloaded_size / (1024*1024):.2f}MB/"
f"{progress.total_size / (1024*1024):.2f}MB) "
f"速度: {progress.speed / (1024*1024):.2f}MB/s "
f"状态: {progress.status}")
try:
# 创建下载任务
task = DownloadTask(
mv_id=mv_id,
quality=quality,
output_dir="./test_downloads/mv/",
max_retries=2,
chunk_size=512 * 1024 # 512KB chunks for testing
)
# 异步下载
async with MVDownloaderNative() as downloader:
success = await downloader.download_mv(task, progress_callback)
print(f"下载结果: {'成功' if success else '失败'}")
return success
except Exception as e:
print(f"异步下载测试失败: {e}")
return False
def test_mv_download_sync(mv_id, quality="480"):
"""测试同步MV下载"""
print("=" * 50)
print("测试同步MV下载")
print("=" * 50)
try:
success = download_mv_sync(
mv_id=mv_id,
quality=quality,
output_dir="./test_downloads/mv/"
)
print(f"同步下载结果: {'成功' if success else '失败'}")
return success
except Exception as e:
print(f"同步下载测试失败: {e}")
return False
async def test_batch_download(mv_ids, quality="240"):
"""测试批量下载"""
print("=" * 50)
print("测试批量下载")
print("=" * 50)
def batch_progress_callback(all_progress: dict):
"""批量下载进度回调"""
completed = sum(1 for p in all_progress.values() if p.status == 'completed')
total = len(all_progress)
print(f"批量下载进度: {completed}/{total} 个任务完成")
for mv_id, progress in all_progress.items():
if progress.status == 'downloading':
print(f" MV {mv_id}: {progress.progress:.1f}% - {progress.filename[:30]}...")
try:
# 创建多个下载任务
tasks = []
for mv_id in mv_ids[:2]: # 只下载前2个进行测试
task = DownloadTask(
mv_id=mv_id,
quality=quality,
output_dir="./test_downloads/batch/",
chunk_size=256 * 1024 # 更小的chunk用于测试
)
tasks.append(task)
# 批量下载
async with MVDownloaderNative() as downloader:
results = await downloader.batch_download(
tasks,
max_concurrent=2,
progress_callback=batch_progress_callback
)
success_count = sum(1 for result in results if result is True)
print(f"批量下载完成: {success_count}/{len(results)} 个任务成功")
return success_count > 0
except Exception as e:
print(f"批量下载测试失败: {e}")
return False
def test_error_handling():
"""测试错误处理"""
print("=" * 50)
print("测试错误处理")
print("=" * 50)
api = NeteaseNativeMVAPI()
# 测试无效MV ID
try:
print("测试无效MV ID...")
mv_info = api.get_mv_detail(999999999)
print("错误:应该抛出异常但没有")
except Exception as e:
print(f"✓ 正确处理无效MV ID: {e}")
# 测试空搜索
try:
print("测试空搜索...")
results = api.search_mv("", limit=1)
print(f"空搜索结果: {len(results)} 个")
except Exception as e:
print(f"空搜索异常: {e}")
# 测试无效画质
try:
print("测试无效画质...")
# 使用一个可能存在的MV ID进行测试
url_infos = api.get_mv_url(5436712, quality="4K") # 不存在的画质
print(f"无效画质测试结果: {len(url_infos)} 个链接")
except Exception as e:
print(f"✓ 正确处理无效画质: {e}")
print("错误处理测试完成")
async def main():
"""主测试函数"""
print("基于原生架构的网易云MV功能测试")
print("基于music_api.py相同的技术架构")
print("使用官方API接口,无需外部服务依赖")
print()
# 创建测试目录
Path("./test_downloads/mv/").mkdir(parents=True, exist_ok=True)
Path("./test_downloads/batch/").mkdir(parents=True, exist_ok=True)
# 1. 测试MV搜索
search_result = test_mv_search()
if not search_result:
print("搜索失败,无法继续后续测试")
return
mv_id = search_result['id']
print(f"使用MV ID {mv_id} 进行后续测试")
# 2. 测试MV详情
mv_info = test_mv_detail(mv_id)
# 3. 测试MV播放链接
url_info = test_mv_url(mv_id)
# 4. 测试MV评论
test_mv_comments(mv_id)
# 5. 测试错误处理
test_error_handling()
# 6. 测试下载功能 (可选,因为需要实际下载文件)
download_test = input("是否测试下载功能? (y/N): ").strip().lower()
if download_test == 'y':
# 异步下载测试
await test_mv_download_async(mv_id, quality="240") # 使用最低画质测试
# 同步下载测试
# test_mv_download_sync(mv_id, quality="240")
# 批量下载测试 (使用搜索结果中的多个MV)
if len(search_result) >= 2:
mv_ids = [result['id'] for result in [search_result]] # 只用一个进行测试
# await test_batch_download(mv_ids, quality="240")
print("\n" + "=" * 50)
print("所有测试完成!")
print("如需实际使用,请参考示例代码")
print("=" * 50)
def example_usage():
"""使用示例"""
print("""
使用示例:
1. 搜索MV:
```python
from mv_api_native import NeteaseNativeMVAPI
api = NeteaseNativeMVAPI()
results = api.search_mv("周杰伦")
for mv in results:
print(f"{mv['artistName']} - {mv['name']} (ID: {mv['id']})")
```
2. 获取MV详情:
```python
mv_info = api.get_mv_detail(5436712)
print(f"MV名称: {mv_info.name}")
print(f"艺术家: {mv_info.artist}")
```
3. 获取播放链接:
```python
url_infos = api.get_mv_url(5436712, quality="720")
for url_info in url_infos:
print(f"{url_info.quality}P: {url_info.url}")
```
4. 同步下载MV:
```python
from mv_downloader_native import download_mv_sync
success = download_mv_sync(5436712, quality="720")
if success:
print("下载成功!")
```
5. 异步下载MV:
```python
from mv_downloader_native import MVDownloaderNative, DownloadTask
async def download_example():
task = DownloadTask(mv_id=5436712, quality="720")
async with MVDownloaderNative() as downloader:
success = await downloader.download_mv(task)
return success
# 运行异步函数
import asyncio
asyncio.run(download_example())
```
""")
if __name__ == "__main__":
# 显示使用示例
example_usage()
# 运行测试
run_test = input("是否运行完整测试? (y/N): ").strip().lower()
if run_test == 'y':
asyncio.run(main())