mirror of
https://github.com/real-zony/ZonyLrcToolsX.git
synced 2026-11-24 03:37:47 +08:00
fix(desktop): 修正解密、配置和任务生命周期问题
修复 KGG/KGM 识别、密钥解码及输出文件保护;改进配置无损保存、登录会话安全和取消处理。统一新增 C# 代码风格,补齐发布许可声明及文档,并增加针对性回归测试。
This commit is contained in:
1 parent
7379571e2d
commit
8912a79168
64 files changed
+2787
-1182
No files matched your search
@@ -0,0 +1,255 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common;
|
||||
using ZonyLrcTools.Common.Album;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Lyrics;
|
||||
|
||||
namespace ZonyLrcTools.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 下载结果、取消与文件保护的回归测试。
|
||||
/// </summary>
|
||||
public sealed class CoreDownloadRegressionTests : IDisposable
|
||||
{
|
||||
private readonly string _directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
private readonly RecordingLogger _logger = new();
|
||||
|
||||
/// <summary>
|
||||
/// 创建独立的输出目录。
|
||||
/// </summary>
|
||||
public CoreDownloadRegressionTests()
|
||||
{
|
||||
Directory.CreateDirectory(_directory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 首个来源无歌词时继续查找后续来源。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Lyrics_EmptyProviderFallsBackAsync()
|
||||
{
|
||||
var info = CreateMusicInfo();
|
||||
var downloader = CreateLyricsDownloader(
|
||||
new TestLyricsProvider("empty", () => new LyricsItemCollection(new GlobalLyricsConfigOptions())),
|
||||
new TestLyricsProvider("available", CreateLyrics));
|
||||
|
||||
await downloader.DownloadAsync([info]);
|
||||
|
||||
Assert.True(info.IsSuccessful);
|
||||
Assert.False(info.IsPruneMusic);
|
||||
Assert.Contains("可用歌词", await File.ReadAllTextAsync(Path.ChangeExtension(info.FilePath, ".lrc")));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 来源失败后仍可使用后续来源。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Lyrics_FailedProviderFallsBackAsync()
|
||||
{
|
||||
var info = CreateMusicInfo();
|
||||
var failure = new InvalidOperationException("来源不可用");
|
||||
var downloader = CreateLyricsDownloader(
|
||||
new TestLyricsProvider("failed", () => throw failure),
|
||||
new TestLyricsProvider("available", CreateLyrics));
|
||||
|
||||
await downloader.DownloadAsync([info]);
|
||||
|
||||
Assert.True(info.IsSuccessful);
|
||||
Assert.False(info.IsPruneMusic);
|
||||
Assert.Contains("可用歌词", await File.ReadAllTextAsync(Path.ChangeExtension(info.FilePath, ".lrc")));
|
||||
Assert.Contains(failure, _logger.Exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取消发生在来源返回之前时保留原歌词。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Lyrics_CancellationPreservesExistingFileAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var info = CreateMusicInfo();
|
||||
var lyricsPath = Path.ChangeExtension(info.FilePath, ".lrc");
|
||||
await File.WriteAllTextAsync(lyricsPath, "原歌词");
|
||||
var downloader = CreateLyricsDownloader(new TestLyricsProvider("cancel", () =>
|
||||
{
|
||||
cancellation.Cancel();
|
||||
return CreateLyrics();
|
||||
}));
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
downloader.DownloadAsync([info], cancellationToken: cancellation.Token));
|
||||
|
||||
Assert.False(info.IsSuccessful);
|
||||
Assert.Equal("原歌词", await File.ReadAllTextAsync(lyricsPath));
|
||||
Assert.Empty(Directory.GetFiles(_directory, "*.tmp"));
|
||||
Assert.Empty(_logger.Exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 没有启用来源时不能将歌曲标记为纯音乐。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Lyrics_NoProvidersReportsFailureAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var info = CreateMusicInfo();
|
||||
var downloader = CreateLyricsDownloader();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => downloader.DownloadAsync([info], callback: _ =>
|
||||
{
|
||||
cancellation.Cancel();
|
||||
return Task.CompletedTask;
|
||||
}, cancellationToken: cancellation.Token));
|
||||
|
||||
Assert.False(info.IsSuccessful);
|
||||
Assert.False(info.IsPruneMusic);
|
||||
Assert.False(File.Exists(Path.ChangeExtension(info.FilePath, ".lrc")));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 已有封面不依赖网络结果,也不会被覆盖。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Album_ExistingFileIsSuccessfulWithoutProviderRequestAsync()
|
||||
{
|
||||
var info = CreateMusicInfo();
|
||||
var albumPath = Path.ChangeExtension(info.FilePath, ".png");
|
||||
await File.WriteAllBytesAsync(albumPath, [1, 2, 3]);
|
||||
var downloader = new AlbumDownloader(
|
||||
[new TestAlbumProvider(() => throw new InvalidOperationException("不应请求来源"))], _logger);
|
||||
|
||||
await downloader.DownloadAsync([info]);
|
||||
|
||||
Assert.True(info.IsSuccessful);
|
||||
Assert.Equal(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(albumPath));
|
||||
Assert.Empty(_logger.Exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 来源返回时已取消则不创建封面。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Album_CancellationDoesNotPublishFileAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var info = CreateMusicInfo();
|
||||
var downloader = new AlbumDownloader([new TestAlbumProvider(() =>
|
||||
{
|
||||
cancellation.Cancel();
|
||||
return [1, 2, 3];
|
||||
})], _logger);
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
downloader.DownloadAsync([info], cancellationToken: cancellation.Token));
|
||||
|
||||
Assert.False(info.IsSuccessful);
|
||||
Assert.Empty(Directory.GetFiles(_directory));
|
||||
Assert.Empty(_logger.Exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 无来源时仍应遵守预先取消的令牌。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Album_NoProvidersHonorsCancellationAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
cancellation.Cancel();
|
||||
var downloader = new AlbumDownloader([], _logger);
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
downloader.DownloadAsync([CreateMusicInfo()], cancellationToken: cancellation.Token));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 日志辅助方法保留异常对象且不重新抛出业务错误。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Logger_PreservesErrorCodeException()
|
||||
{
|
||||
var exception = new ErrorCodeException(ErrorCodes.NotSupportedFileEncoding);
|
||||
|
||||
_logger.LogWarningInfo(exception);
|
||||
|
||||
Assert.Same(exception, Assert.Single(_logger.Exceptions));
|
||||
}
|
||||
|
||||
private MusicInfo CreateMusicInfo() => new(Path.Combine(_directory, "歌曲.mp3"), "歌曲", "歌手");
|
||||
|
||||
private static LyricsItemCollection CreateLyrics() => new(new GlobalLyricsConfigOptions())
|
||||
{
|
||||
new(0, 1, "可用歌词")
|
||||
};
|
||||
|
||||
private LyricsDownloader CreateLyricsDownloader(params TestLyricsProvider[] providers)
|
||||
{
|
||||
var options = new GlobalOptions
|
||||
{
|
||||
Provider = new ProviderOptions
|
||||
{
|
||||
Lyric = new LyricsOptions
|
||||
{
|
||||
Config = new GlobalLyricsConfigOptions(),
|
||||
Plugin = providers.Select((provider, index) => new LyricsProviderOptions
|
||||
{
|
||||
Name = provider.DownloaderName,
|
||||
Priority = index
|
||||
}).ToArray()
|
||||
}
|
||||
}
|
||||
};
|
||||
return new LyricsDownloader(providers, Options.Create(options), _logger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除测试生成的输出。
|
||||
/// </summary>
|
||||
public void Dispose() => Directory.Delete(_directory, true);
|
||||
|
||||
private sealed class TestLyricsProvider(string name, Func<LyricsItemCollection> download) : ILyricsProvider
|
||||
{
|
||||
public string DownloaderName => name;
|
||||
|
||||
public ValueTask<LyricsItemCollection> DownloadAsync(string songName, string artist, long? duration = null)
|
||||
=> ValueTask.FromResult(download());
|
||||
}
|
||||
|
||||
private sealed class TestAlbumProvider(Func<byte[]> download) : IAlbumProvider
|
||||
{
|
||||
public string DownloaderName => InternalAlbumProviderNames.NetEase;
|
||||
|
||||
public ValueTask<byte[]> DownloadAsync(string songName, string artist) => ValueTask.FromResult(download());
|
||||
}
|
||||
|
||||
private sealed class RecordingLogger : IWarpLogger
|
||||
{
|
||||
public List<Exception> Exceptions { get; } = [];
|
||||
|
||||
public Task DebugAsync(string message, Exception? exception = null) => RecordAsync(exception);
|
||||
public Task InfoAsync(string message, Exception? exception = null) => RecordAsync(exception);
|
||||
public Task WarnAsync(string message, Exception? exception = null) => RecordAsync(exception);
|
||||
public Task ErrorAsync(string message, Exception? exception = null) => RecordAsync(exception);
|
||||
|
||||
private Task RecordAsync(Exception? exception)
|
||||
{
|
||||
if (exception != null)
|
||||
{
|
||||
Exceptions.Add(exception);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicScanner;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 扫码登录对话框的状态与关闭行为测试。
|
||||
/// </summary>
|
||||
public class DesktopInteractionQrCodeLoginTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 重复收到窗口关闭通知时只取消一次登录。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void NotifyClosed_CancelsLoginOnlyOnce()
|
||||
{
|
||||
var viewModel = new QrCodeLoginViewModel();
|
||||
var cancellationCount = 0;
|
||||
viewModel.Cancelled += (_, _) => cancellationCount++;
|
||||
|
||||
viewModel.NotifyClosed();
|
||||
viewModel.NotifyClosed();
|
||||
|
||||
Assert.Equal(1, cancellationCount);
|
||||
Assert.False(viewModel.IsCompleted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 登录成功导致的窗口关闭不应触发取消。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Complete_ClosesDialogWithoutCancellingLogin()
|
||||
{
|
||||
var viewModel = new QrCodeLoginViewModel();
|
||||
var cancellationCount = 0;
|
||||
var closeRequestCount = 0;
|
||||
viewModel.Cancelled += (_, _) => cancellationCount++;
|
||||
viewModel.CloseRequested += (_, _) =>
|
||||
{
|
||||
closeRequestCount++;
|
||||
viewModel.NotifyClosed();
|
||||
};
|
||||
|
||||
viewModel.Complete();
|
||||
|
||||
Assert.True(viewModel.IsCompleted);
|
||||
Assert.Equal(1, closeRequestCount);
|
||||
Assert.Equal(0, cancellationCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 已关闭的窗口不再接受迟到的登录结果。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void NotifyClosed_IgnoresLateLoginCallbacks()
|
||||
{
|
||||
var viewModel = new QrCodeLoginViewModel();
|
||||
var statusBeforeClosing = viewModel.StatusText;
|
||||
var closeRequestCount = 0;
|
||||
viewModel.CloseRequested += (_, _) => closeRequestCount++;
|
||||
viewModel.NotifyClosed();
|
||||
|
||||
viewModel.SetState(NetEaseLoginState.Succeeded);
|
||||
viewModel.SetError("迟到的网络错误");
|
||||
viewModel.Complete();
|
||||
|
||||
Assert.False(viewModel.IsCompleted);
|
||||
Assert.Equal(statusBeforeClosing, viewModel.StatusText);
|
||||
Assert.Equal(0, closeRequestCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 二维码过期后不应继续显示等待扫码。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void SetState_ExpiredStopsShowingWaitingStatus()
|
||||
{
|
||||
var viewModel = new QrCodeLoginViewModel();
|
||||
viewModel.SetState(NetEaseLoginState.Waiting);
|
||||
var waitingStatus = viewModel.StatusText;
|
||||
|
||||
viewModel.SetState(NetEaseLoginState.Expired);
|
||||
|
||||
Assert.NotEqual(waitingStatus, viewModel.StatusText);
|
||||
Assert.False(viewModel.IsCompleted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using YamlDotNet.RepresentationModel;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure;
|
||||
|
||||
/// <summary>设置文件无损修改的回归测试。</summary>
|
||||
public sealed class DesktopSettingsPersistenceTests
|
||||
{
|
||||
/// <summary>会话与数据库路径使用生成的 JSON 元数据往返,敏感会话文件限制权限。</summary>
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task RoundTripsStateUsingGeneratedMetadataAsync(bool isSession)
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
var path = Path.Combine(directory, "state.json");
|
||||
try
|
||||
{
|
||||
var assembly = typeof(NetEaseSession).Assembly;
|
||||
var contextType = assembly.GetType("ZonyLrcTools.Desktop.Infrastructure.Configuration.DesktopStateJsonContext")!;
|
||||
var context = (JsonSerializerContext)contextType.GetProperty("Default")!.GetValue(null)!;
|
||||
var value = isSession
|
||||
? (object)new NetEaseSession { Cookie = "test-cookie", CsrfToken = "test-token" }
|
||||
: new KugouDatabaseSetting { DatabasePath = "/music/My Database.db" };
|
||||
var typeInfo = context.GetTypeInfo(value.GetType())!;
|
||||
var writer = assembly.GetType("ZonyLrcTools.Desktop.Infrastructure.Configuration.DesktopStateFile")!;
|
||||
var method = writer.GetMethod("WriteAsync", BindingFlags.Static | BindingFlags.NonPublic)!
|
||||
.MakeGenericMethod(value.GetType());
|
||||
await (Task)method.Invoke(null, new object[]
|
||||
{
|
||||
path, value, typeInfo, isSession, CancellationToken.None
|
||||
})!;
|
||||
|
||||
var loaded = JsonSerializer.Deserialize(await File.ReadAllTextAsync(path), typeInfo);
|
||||
if (isSession)
|
||||
{
|
||||
var session = loaded.ShouldBeOfType<NetEaseSession>();
|
||||
session.Cookie.ShouldBe("test-cookie");
|
||||
session.CsrfToken.ShouldBe("test-token");
|
||||
}
|
||||
else
|
||||
{
|
||||
loaded.ShouldBeOfType<KugouDatabaseSetting>().DatabasePath.ShouldBe("/music/My Database.db");
|
||||
}
|
||||
if (isSession && !OperatingSystem.IsWindows())
|
||||
{
|
||||
File.GetUnixFileMode(path).ShouldBe(UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
Directory.GetFiles(directory, "*.tmp").ShouldBeEmpty();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(directory))
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>更改其他设置不能覆盖手工配置的换行符。</summary>
|
||||
[Fact]
|
||||
public void KeepsCustomLineBreakWhenChangingProxy()
|
||||
{
|
||||
var options = new GlobalOptions
|
||||
{
|
||||
Provider = new ProviderOptions
|
||||
{
|
||||
Lyric = new LyricsOptions
|
||||
{
|
||||
Config = new GlobalLyricsConfigOptions { LineBreak = string.Empty, FileEncoding = "ascii" },
|
||||
Plugin = Array.Empty<LyricsProviderOptions>()
|
||||
}
|
||||
}
|
||||
};
|
||||
var viewModel = new SettingsViewModel(new MemorySettingsStore(options));
|
||||
viewModel.IsProxyEnabled = true;
|
||||
options.Provider.Lyric.Config.LineBreak.ShouldBe(string.Empty);
|
||||
viewModel.AvailableEncodings.ShouldContain("ascii");
|
||||
}
|
||||
|
||||
/// <summary>恢复默认值同时恢复下载器顺序。</summary>
|
||||
[Fact]
|
||||
public async Task ResetRestoresProviderOrderAsync()
|
||||
{
|
||||
var options = new GlobalOptions
|
||||
{
|
||||
Provider = new ProviderOptions
|
||||
{
|
||||
Lyric = new LyricsOptions
|
||||
{
|
||||
Config = new GlobalLyricsConfigOptions(),
|
||||
Plugin = new[]
|
||||
{
|
||||
new LyricsProviderOptions { Name = "QQ", Priority = 1 },
|
||||
new LyricsProviderOptions { Name = "NetEase", Priority = -1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
var viewModel = new SettingsViewModel(new MemorySettingsStore(options));
|
||||
await viewModel.ResetToDefaultsCommand.ExecuteAsync(null);
|
||||
viewModel.LyricsProviders[0].Name.ShouldBe("NetEase");
|
||||
viewModel.LyricsProviders[0].Priority.ShouldBe(1);
|
||||
viewModel.LyricsProviders[0].IsEnabled.ShouldBeTrue();
|
||||
viewModel.ProxyPort.ShouldBe(4780);
|
||||
}
|
||||
|
||||
private sealed class MemorySettingsStore(GlobalOptions options) : ISettingsStore
|
||||
{
|
||||
public GlobalOptions Options { get; } = options;
|
||||
public string ConfigFilePath => "unused.yaml";
|
||||
public Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(SettingsSaveResult.Success(ConfigFilePath));
|
||||
}
|
||||
|
||||
/// <summary>合法的 YAML 写法不应导致未知字段和注释丢失。</summary>
|
||||
[Theory]
|
||||
[InlineData("# keep\nnetworkOptions: {isEnable: false, ip: localhost, port: 80}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nprovider:\n tag:\n blockWord:\n filePath: My Words.json # dictionary\ncustom: keep\n", "provider.tag.blockWord.filePath", "New Words.json")]
|
||||
[InlineData("# keep\nnetworkOptions:\n isEnable: false\n ip: localhost\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {isEnable: false, ip: localhost}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {ip: localhost,}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
public async Task PatchesValidYamlWithoutDiscardingUnmanagedValuesAsync(string yaml, string key, string value)
|
||||
{
|
||||
var path = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
await File.WriteAllTextAsync(path, yaml);
|
||||
using var store = new SettingsStore(Options.Create(new GlobalOptions()));
|
||||
var method = typeof(SettingsStore).GetMethod("TryPatchInPlaceAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
var result = await (Task<string?>)method.Invoke(store, new object[]
|
||||
{
|
||||
path, new Dictionary<string, string> { [key] = value }, CancellationToken.None
|
||||
})!;
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
result.ShouldContain("# keep");
|
||||
var stream = new YamlStream();
|
||||
stream.Load(new StringReader(result!));
|
||||
var mapping = (YamlMappingNode)stream.Documents[0].RootNode;
|
||||
((YamlScalarNode)mapping.Children[new YamlScalarNode("custom")]).Value.ShouldBe("keep");
|
||||
var node = (YamlNode)mapping;
|
||||
foreach (var part in key.Split('.'))
|
||||
{
|
||||
node = ((YamlMappingNode)node).Children[new YamlScalarNode(part)];
|
||||
}
|
||||
((YamlScalarNode)node).Value.ShouldBe(value);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>无效文件必须保留,不能用内存配置覆盖。</summary>
|
||||
[Fact]
|
||||
public async Task RefusesMalformedYamlAsync()
|
||||
{
|
||||
var path = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
const string original = "networkOptions: [broken\n# keep";
|
||||
await File.WriteAllTextAsync(path, original);
|
||||
using var store = new SettingsStore(Options.Create(new GlobalOptions()));
|
||||
var method = typeof(SettingsStore).GetMethod("TryPatchInPlaceAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
await Should.ThrowAsync<Exception>(async () => await (Task<string?>)method.Invoke(store, new object[]
|
||||
{
|
||||
path, new Dictionary<string, string> { ["networkOptions.port"] = "8080" }, CancellationToken.None
|
||||
})!);
|
||||
(await File.ReadAllTextAsync(path)).ShouldBe(original);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicDecryption;
|
||||
using ZonyLrcTools.Common.MusicDecryption.Kugou;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用合成加密 SQLite 数据验证密钥读取,不依赖真实酷狗数据库。
|
||||
/// </summary>
|
||||
public sealed class KggDatabaseRegressionTests : IDisposable
|
||||
{
|
||||
private readonly string _directory = Directory.CreateTempSubdirectory("zony-kgg-db-tests-").FullName;
|
||||
|
||||
/// <summary>
|
||||
/// 通过 SQLite 查询完整的合成加密数据库,并保持原文件不变。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ReadEncryptionKeys_ReadsEncryptedDatabaseWithoutChangingSource()
|
||||
{
|
||||
var path = CreateEncryptedDatabase("keys;test.db");
|
||||
var original = File.ReadAllBytes(path);
|
||||
|
||||
var keys = KugouEkeyDatabase.ReadEncryptionKeys(path, out var failureReason);
|
||||
|
||||
Assert.Null(failureReason);
|
||||
Assert.Equal("synthetic-ekey", keys["audio-hash"]);
|
||||
Assert.Equal(original, File.ReadAllBytes(path));
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 区分大小写的文件系统上,切换路径大小写必须重新加载数据库。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void SetDatabasePath_ReloadsDistinctCaseSensitivePath()
|
||||
{
|
||||
var lowerPath = Path.Combine(_directory, "keys.db");
|
||||
var upperPath = Path.Combine(_directory, "KEYS.db");
|
||||
File.WriteAllText(lowerPath, "invalid database");
|
||||
if (File.Exists(upperPath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CreateEncryptedDatabase("KEYS.db");
|
||||
var provider = new KugouKeyProvider();
|
||||
provider.SetDatabasePath(lowerPath);
|
||||
Assert.False(provider.Probe().IsAvailable);
|
||||
|
||||
provider.SetDatabasePath(upperPath);
|
||||
|
||||
Assert.True(provider.Probe().IsAvailable);
|
||||
Assert.Equal("synthetic-ekey", provider.FindKey("audio-hash"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除本测试创建的数据。
|
||||
/// </summary>
|
||||
public void Dispose() => Directory.Delete(_directory, true);
|
||||
|
||||
private string CreateEncryptedDatabase(string name)
|
||||
{
|
||||
var path = Path.Combine(_directory, name);
|
||||
var connectionString = new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString();
|
||||
using (var connection = new SqliteConnection(connectionString))
|
||||
{
|
||||
connection.Open();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "PRAGMA page_size=1024; CREATE TABLE ShareFileItems (EncryptionKeyId TEXT, EncryptionKey TEXT);"
|
||||
+ "INSERT INTO ShareFileItems VALUES ('audio-hash', 'synthetic-ekey');";
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
using var aes = Aes.Create();
|
||||
var derivation = new byte[24];
|
||||
for (var page = 1; page <= bytes.Length / 1024; page++)
|
||||
{
|
||||
Convert.FromHexString("1D613145B247BF7F3D189672144FE4BF").CopyTo(derivation, 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(16), (uint)page);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(20), 0x546C4173);
|
||||
aes.Key = MD5.HashData(derivation);
|
||||
var value = (uint)page + 1;
|
||||
for (var index = 0; index < 16; index += 4)
|
||||
{
|
||||
value = unchecked(0x9EF4 * value - 0x7FFFFF07 * (value / 0xCE26));
|
||||
if ((value & 0x80000000) != 0)
|
||||
{
|
||||
value = unchecked(value + 0x7FFFFF07);
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(index), value);
|
||||
}
|
||||
|
||||
var iv = MD5.HashData(derivation.AsSpan(0, 16));
|
||||
var offset = (page - 1) * 1024;
|
||||
if (page == 1)
|
||||
{
|
||||
var header = bytes.AsSpan(16, 8).ToArray();
|
||||
var encrypted = aes.EncryptCbc(bytes.AsSpan(16, 1008), iv, PaddingMode.None);
|
||||
encrypted.CopyTo(bytes, 16);
|
||||
encrypted.AsSpan(0, 8).CopyTo(bytes.AsSpan(8));
|
||||
header.CopyTo(bytes, 16);
|
||||
}
|
||||
else
|
||||
{
|
||||
var encrypted = aes.EncryptCbc(bytes.AsSpan(offset, 1024), iv, PaddingMode.None);
|
||||
encrypted.CopyTo(bytes, offset);
|
||||
}
|
||||
}
|
||||
|
||||
File.WriteAllBytes(path, bytes);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicDecryption;
|
||||
using ZonyLrcTools.Common.MusicDecryption.Kugou;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用独立合成数据验证 KGG 解密边界,不代表真实客户端样本。
|
||||
/// </summary>
|
||||
public sealed class KggRegressionTests : IDisposable
|
||||
{
|
||||
private const string Ekey = "AQIDBAUGBwg0ENpQsPOCXXtClrT99x6WMpfYT1U/+p8=";
|
||||
private readonly string _directory = Directory.CreateTempSubdirectory("zony-kgg-tests-").FullName;
|
||||
|
||||
/// <summary>
|
||||
/// 无填充 Base64 的末组三个字符不能丢掉第二个字节。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Decode_UnpaddedEkey_PreservesEveryKeyByte()
|
||||
{
|
||||
var result = EkeyDecoder.Decode(Ekey.TrimEnd('='), out var invalidCount);
|
||||
|
||||
Assert.Equal(Enumerable.Range(1, 16).Select(value => (byte)value), result);
|
||||
Assert.Equal(0, invalidCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 填充之后还有数据的 Base64 是损坏密钥,不能静默忽略。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Decode_RejectsDataAfterPadding()
|
||||
{
|
||||
Assert.Empty(EkeyDecoder.Decode(Ekey + "AAAA"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// QMC 查表算法使用相同位移量左右移位,不是循环移位。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void MapCipher_UsesReferenceMask()
|
||||
{
|
||||
var cipher = Qmc2Cipher.Create([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
var data = new byte[8];
|
||||
|
||||
cipher!.Decrypt(data, 0);
|
||||
|
||||
Assert.Equal(new byte[] { 29, 65, 192, 65, 29, 65, 192, 65 }, data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合成密文必须还原为预先确定的音频字节。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_DecryptsSyntheticFile()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.True(result.IsSuccess, result.ErrorMessage);
|
||||
Assert.Equal("fLaCtest-payload"u8.ToArray(), File.ReadAllBytes(result.OutputFilePath!));
|
||||
Assert.Single(Directory.GetFiles(_directory, "*.flac"));
|
||||
Assert.Empty(Directory.GetFiles(_directory, "*.part"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同名文件不论长度是否相同,都不能覆盖或冒充本次成功结果。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(16)]
|
||||
[InlineData(3)]
|
||||
public async Task ConvertAsync_PreservesExistingOutput(int length)
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var output = Path.ChangeExtension(input, ".flac");
|
||||
var original = Enumerable.Repeat((byte)0x42, length).ToArray();
|
||||
File.WriteAllBytes(output, original);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Equal(original, File.ReadAllBytes(output));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 旧版 KGM 与 KGG 魔数相同,不能将旧格式误送到 KGG 解密器。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(2u)]
|
||||
[InlineData(3u)]
|
||||
public void IsKggFile_DoesNotCaptureLegacyKgm(uint version)
|
||||
{
|
||||
var path = CreateKgg();
|
||||
var data = File.ReadAllBytes(path);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x14), version);
|
||||
File.WriteAllBytes(path, data);
|
||||
|
||||
Assert.False(KggMusicDecryptor.IsKggFile(path));
|
||||
Assert.False(new KugouKeyProvider().IsKggFile(path));
|
||||
Assert.Null(new KugouKeyProvider().ReadAudioHash(path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 不能覆盖另一个任务或程序的临时文件。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_PreservesUnownedPartialFile()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var partialPath = Path.ChangeExtension(input, ".flac") + ".part";
|
||||
File.WriteAllText(partialPath, "other conversion");
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.True(result.IsSuccess, result.ErrorMessage);
|
||||
Assert.Equal("other conversion", File.ReadAllText(partialPath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 音频偏移不能指向头部或文件末尾之外。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(0u)]
|
||||
[InlineData(1023u)]
|
||||
[InlineData(uint.MaxValue)]
|
||||
public async Task ConvertAsync_RejectsInvalidAudioOffset(uint offset)
|
||||
{
|
||||
var input = CreateKgg(offset);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 损坏的音频头不能默认为 MP3 并报告成功。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_RejectsUnknownAudioHeader()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var bytes = File.ReadAllBytes(input);
|
||||
bytes[1024] ^= 0xFF;
|
||||
File.WriteAllBytes(input, bytes);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查找密钥期间取消后,不应继续发布输出文件。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_CancellationDoesNotPublishOutput()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
KggMusicDecryptor.ConvertAsync(input, new KeyProvider(cancellation.Cancel), cancellation.Token));
|
||||
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除本测试创建的数据。
|
||||
/// </summary>
|
||||
public void Dispose() => Directory.Delete(_directory, true);
|
||||
|
||||
private string CreateKgg(uint offset = 1024)
|
||||
{
|
||||
var encryptedAudio = Convert.FromHexString("59CEA1024B24B3F612F2A138532EA1E6");
|
||||
var data = new byte[1024 + encryptedAudio.Length];
|
||||
Convert.FromHexString("7CD532EB86027F4BA8AFA68E0FFF9914").CopyTo(data, 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x10), offset);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x14), 5);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x44), 32);
|
||||
"0123456789abcdef0123456789abcdef"u8.CopyTo(data.AsSpan(0x48));
|
||||
encryptedAudio.CopyTo(data, 1024);
|
||||
var path = Path.Combine(_directory, "song.kgg");
|
||||
File.WriteAllBytes(path, data);
|
||||
return path;
|
||||
}
|
||||
|
||||
private sealed class KeyProvider(Action? onFind = null) : IKugouKeyProvider
|
||||
{
|
||||
public string DatabasePath => "synthetic-key-source";
|
||||
public void SetDatabasePath(string? path) => throw new NotSupportedException();
|
||||
public KugouDatabaseInfo Probe() => new(true, DatabasePath, 1, "合成密钥");
|
||||
public void Invalidate() => throw new NotSupportedException();
|
||||
public bool IsKggFile(string filePath) => throw new NotSupportedException();
|
||||
public string? ReadAudioHash(string filePath) => throw new NotSupportedException();
|
||||
public string? FindKey(string audioHash)
|
||||
{
|
||||
onFind?.Invoke();
|
||||
return audioHash == "0123456789abcdef0123456789abcdef" ? Ekey : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.IO;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
@@ -7,16 +8,31 @@ using ZonyLrcTools.Common.MusicDecryption;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用真实 NCM 样本验证解密。
|
||||
/// </summary>
|
||||
public class NcmMusicDecryptorTests : TestBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 每次使用独立目录,避免历史输出影响解密结果。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertMusicAsync_Test()
|
||||
public async Task ConvertMusicAsync_DecryptsNcmAsync()
|
||||
{
|
||||
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
|
||||
var ncmFilePath = Path.Combine(Directory.GetCurrentDirectory(), "MusicFiles", "Loren Gray - Queen.ncm");
|
||||
var directory = Directory.CreateTempSubdirectory("zony-ncm-tests-").FullName;
|
||||
try
|
||||
{
|
||||
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
|
||||
var ncmFilePath = Path.Combine(directory, "Loren Gray - Queen.ncm");
|
||||
File.Copy(Path.Combine(AppContext.BaseDirectory, "MusicFiles", "Loren Gray - Queen.ncm"), ncmFilePath);
|
||||
|
||||
var result = await decryptor.ConvertMusicAsync(ncmFilePath);
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
var result = await decryptor.ConvertMusicAsync(ncmFilePath);
|
||||
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.Network;
|
||||
|
||||
/// <summary>
|
||||
/// 验证等待服务器响应时可以取消请求。
|
||||
/// </summary>
|
||||
public class WarpHttpCancellationTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 服务端未响应时,取消操作应及时结束请求。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task CancelsPendingRequestAsync(bool isPost)
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var endpoint = (IPEndPoint)listener.LocalEndpoint;
|
||||
var url = $"http://127.0.0.1:{endpoint.Port}/";
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var client = new DefaultWarpHttpClient(new LocalClientFactory());
|
||||
var request = SendRequestAsync(client, url, isPost, cancellation.Token);
|
||||
|
||||
using var connection = await listener.AcceptTcpClientAsync().WaitAsync(TimeSpan.FromSeconds(5));
|
||||
cancellation.Cancel();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => request.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||
}
|
||||
|
||||
private static async Task SendRequestAsync(IWarpHttpClient client, string url, bool isPost,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (isPost)
|
||||
{
|
||||
using var response = await client.PostReturnHttpResponseAsync(url, cancellationToken: cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
await client.GetAsync(url, cancellationToken: cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class LocalClientFactory : IHttpClientFactory
|
||||
{
|
||||
public HttpClient CreateClient(string name)
|
||||
{
|
||||
return new HttpClient(new SocketsHttpHandler { UseProxy = false });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicScanner;
|
||||
|
||||
namespace ZonyLrcTools.Tests.MusicScanner;
|
||||
|
||||
/// <summary>
|
||||
/// CSV 换行符与取消行为的回归测试。
|
||||
/// </summary>
|
||||
public sealed class CsvNewlineRegressionTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 各平台导出的 CSV 均可读取并去除字段两端空白。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("\n")]
|
||||
[InlineData("\r\n")]
|
||||
[InlineData("\r")]
|
||||
public async Task Scan_AcceptsPlatformNewlinesAsync(string newline)
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var path = Path.Combine(directory, "songs.csv");
|
||||
try
|
||||
{
|
||||
await File.WriteAllTextAsync(path,
|
||||
$"Name,Artist{newline} Song One , Artist One {newline}{newline}Song Two,Artist Two{newline}",
|
||||
new UTF8Encoding(true));
|
||||
var scanner = new CsvFileMusicScanner();
|
||||
|
||||
var songs = await scanner.GetMusicInfoFromCsvFileAsync(path, directory, "{Artist} - {Name}.lrc");
|
||||
|
||||
Assert.Equal(2, songs.Count);
|
||||
Assert.Equal("Song One", songs[0].Name);
|
||||
Assert.Equal("Artist One", songs[0].Artist);
|
||||
Assert.Equal(Path.Combine(directory, "Artist Two - Song Two.lrc"), songs[1].FilePath);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 已取消的扫描不再访问文件。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Scan_PreCanceledDoesNotReadFileAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
cancellation.Cancel();
|
||||
var scanner = new CsvFileMusicScanner();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => scanner.GetMusicInfoFromCsvFileAsync(
|
||||
Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"), "missing.csv"),
|
||||
Path.GetTempPath(), "{Name}.lrc", cancellation.Token));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.MusicScanner;
|
||||
|
||||
namespace ZonyLrcTools.Tests.MusicScanner;
|
||||
|
||||
/// <summary>
|
||||
/// 网易云登录状态、并发与 HTTP 错误的回归测试。
|
||||
/// </summary>
|
||||
public sealed class NetEaseSessionRegressionTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 登录成功回调只能在 Cookie 保存后发出。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_SuccessCallbackSeesCommittedSessionAsync()
|
||||
{
|
||||
using var handler = new TestHandler((request, _) => Task.FromResult(
|
||||
IsKeyRequest(request) ? KeyResponse() : SuccessResponse()));
|
||||
var scanner = CreateScanner(handler);
|
||||
var observedLogin = false;
|
||||
|
||||
var success = await scanner.LoginAsync(_ => { }, state =>
|
||||
{
|
||||
if (state == NetEaseLoginState.Succeeded)
|
||||
{
|
||||
observedLogin = scanner.IsLoggedIn && scanner.CsrfToken == "csrf-value";
|
||||
}
|
||||
});
|
||||
|
||||
Assert.True(success);
|
||||
Assert.True(observedLogin);
|
||||
Assert.Contains("MUSIC_U=session-value", scanner.Cookie);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 并发登录复用已经建立的会话,不生成互相干扰的二维码。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_ConcurrentRequestsUseOneQrSessionAsync()
|
||||
{
|
||||
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var keyRequests = 0;
|
||||
using var handler = new TestHandler(async (request, cancellationToken) =>
|
||||
{
|
||||
if (IsKeyRequest(request))
|
||||
{
|
||||
Interlocked.Increment(ref keyRequests);
|
||||
await releaseKey.Task.WaitAsync(cancellationToken);
|
||||
return KeyResponse();
|
||||
}
|
||||
|
||||
return SuccessResponse();
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
|
||||
var first = scanner.LoginAsync(_ => { });
|
||||
var second = scanner.LoginAsync(_ => { });
|
||||
releaseKey.SetResult();
|
||||
var results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.All(results, result => Assert.True(result));
|
||||
Assert.Equal(1, keyRequests);
|
||||
Assert.True(scanner.IsLoggedIn);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清除登录后,迟到的扫码结果不能恢复已退出的会话。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_ClearStateRejectsPendingResultAsync()
|
||||
{
|
||||
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var handler = new TestHandler(async (request, cancellationToken) =>
|
||||
{
|
||||
if (IsKeyRequest(request))
|
||||
{
|
||||
await releaseKey.Task.WaitAsync(cancellationToken);
|
||||
return KeyResponse();
|
||||
}
|
||||
|
||||
return SuccessResponse();
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
var login = scanner.LoginAsync(_ => { });
|
||||
|
||||
scanner.ClearLoginState();
|
||||
releaseKey.SetResult();
|
||||
var success = await login.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.False(success);
|
||||
Assert.False(scanner.IsLoggedIn);
|
||||
Assert.Empty(scanner.CsrfToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 恢复的会话不能被旧扫码请求覆盖。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_RestoreStateRejectsPendingResultAsync()
|
||||
{
|
||||
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var handler = new TestHandler(async (request, cancellationToken) =>
|
||||
{
|
||||
if (IsKeyRequest(request))
|
||||
{
|
||||
await releaseKey.Task.WaitAsync(cancellationToken);
|
||||
return KeyResponse();
|
||||
}
|
||||
|
||||
return SuccessResponse();
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
var login = scanner.LoginAsync(_ => { });
|
||||
|
||||
scanner.RestoreLoginState("MUSIC_U=restored", "restored-csrf");
|
||||
releaseKey.SetResult();
|
||||
await login.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.Equal("MUSIC_U=restored", scanner.Cookie);
|
||||
Assert.Equal("restored-csrf", scanner.CsrfToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// HTTP 失败不能被响应中的成功业务码掩盖。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_HttpFailureIsNotSuccessfulAsync()
|
||||
{
|
||||
using var handler = new TestHandler((request, _) =>
|
||||
{
|
||||
var response = IsKeyRequest(request) ? KeyResponse() : SuccessResponse();
|
||||
response.StatusCode = HttpStatusCode.ServiceUnavailable;
|
||||
return Task.FromResult(response);
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
|
||||
await Assert.ThrowsAsync<HttpRequestException>(() => scanner.LoginAsync(_ => { }));
|
||||
|
||||
Assert.False(scanner.IsLoggedIn);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 非扫码状态业务码应失败,而不是永久等待扫码。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("{\"code\":500}")]
|
||||
[InlineData("{\"code\":803}")]
|
||||
public async Task Login_InvalidPollResponseFailsAsync(string body)
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
using var handler = new TestHandler((request, _) => Task.FromResult(
|
||||
IsKeyRequest(request) ? KeyResponse() : JsonResponse(body)));
|
||||
var scanner = CreateScanner(handler);
|
||||
|
||||
await Assert.ThrowsAsync<ErrorCodeException>(() =>
|
||||
scanner.LoginAsync(_ => { }, cancellationToken: cancellation.Token));
|
||||
|
||||
Assert.False(scanner.IsLoggedIn);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 二维码过期时结束登录并通知调用方。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_ExpiredQrReturnsFalseAsync()
|
||||
{
|
||||
using var handler = new TestHandler((request, _) => Task.FromResult(
|
||||
IsKeyRequest(request) ? KeyResponse() : JsonResponse("{\"code\":800}")));
|
||||
var scanner = CreateScanner(handler);
|
||||
var lastState = NetEaseLoginState.Waiting;
|
||||
|
||||
var success = await scanner.LoginAsync(_ => { }, state => lastState = state);
|
||||
|
||||
Assert.False(success);
|
||||
Assert.Equal(NetEaseLoginState.Expired, lastState);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 关闭扫码窗口可以取消正在等待的 HTTP 请求。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_CancellationReachesHttpRequestAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var handler = new TestHandler(async (_, cancellationToken) =>
|
||||
{
|
||||
started.SetResult();
|
||||
await Task.Delay(Timeout.Infinite, cancellationToken);
|
||||
return KeyResponse();
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
var login = scanner.LoginAsync(_ => { }, cancellationToken: cancellation.Token);
|
||||
await started.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
cancellation.Cancel();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => login.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||
Assert.False(scanner.IsLoggedIn);
|
||||
}
|
||||
|
||||
private static NetEaseMusicSongListMusicScanner CreateScanner(HttpMessageHandler handler)
|
||||
=> new(new DefaultWarpHttpClient(new TestClientFactory(handler)),
|
||||
NullLogger<NetEaseMusicSongListMusicScanner>.Instance);
|
||||
|
||||
private static bool IsKeyRequest(HttpRequestMessage request)
|
||||
=> request.RequestUri!.AbsolutePath.EndsWith("/unikey", StringComparison.Ordinal);
|
||||
|
||||
private static HttpResponseMessage KeyResponse() => JsonResponse("{\"code\":200,\"unikey\":\"qr-key\"}");
|
||||
|
||||
private static HttpResponseMessage SuccessResponse()
|
||||
{
|
||||
var response = JsonResponse("{\"code\":803}");
|
||||
response.Headers.TryAddWithoutValidation("Set-Cookie", new[]
|
||||
{
|
||||
"MUSIC_U=session-value; Path=/; Domain=music.163.com; HttpOnly",
|
||||
"__csrf=csrf-value; Path=/; Domain=music.163.com"
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
private static HttpResponseMessage JsonResponse(string body)
|
||||
=> new(HttpStatusCode.OK) { Content = new StringContent(body) };
|
||||
|
||||
private sealed class TestClientFactory(HttpMessageHandler handler) : IHttpClientFactory
|
||||
{
|
||||
public HttpClient CreateClient(string name) => new(handler, disposeHandler: false);
|
||||
}
|
||||
|
||||
private sealed class TestHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> send)
|
||||
: HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
=> send(request, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ZonyLrcTools.Cli\ZonyLrcTools.Cli.csproj" />
|
||||
<ProjectReference Include="..\..\src\ZonyLrcTools.Desktop\ZonyLrcTools.Desktop.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Reference in new issue
Block a user