File size: 11,989 Bytes
3b08e6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"""基于原生架构的网易云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())