using System.ComponentModel;
using System.Diagnostics;
using Moq;
using NewLife;
using NewLife.Caching;
using NewLife.Remoting;
using Stardust;
using Stardust.Registry;
using Stardust.Storages;
using Xunit;
namespace Stardust.Tests;
/// <summary>测试用文件存储子类。DefaultFileStorage 无抽象成员,直接继承即可</summary>
internal class TestFileStorage : DefaultFileStorage
{
/// <summary>下载次数</summary>
public Int32 FetchCount;
/// <summary>前多少次下载失败</summary>
public Int32 FetchFailures;
/// <summary>下载写入的内容</summary>
public String FetchContent = "hello";
/// <summary>下载耗时</summary>
public TimeSpan FetchDelay = TimeSpan.FromMilliseconds(100);
/// <summary>暴露受保护的本地文件校验方法,便于测试</summary>
/// <param name="path">相对路径</param>
/// <param name="hash">哈希</param>
public new Boolean CheckLocalFile(String? path, String? hash) => base.CheckLocalFile(path, hash);
/// <summary>暴露受保护的新文件处理入口,便于测试并发合并</summary>
/// <param name="info">新文件消息</param>
/// <param name="cancellationToken">取消通知</param>
public Task OnNewFileInfoAsync(NewFileInfo info, CancellationToken cancellationToken = default)
=> base.OnNewFileInfoAsync(info, null!, cancellationToken);
/// <summary>暴露受保护的文件锁入口,便于测试跨进程锁</summary>
/// <param name="fileName">文件完整路径</param>
/// <param name="hash">文件哈希</param>
/// <param name="cancellationToken">取消通知</param>
public new Task<FileStream?> AcquireFileLockAsync(String fileName, String? hash, CancellationToken cancellationToken = default)
=> base.AcquireFileLockAsync(fileName, hash, cancellationToken);
/// <summary>模拟下载。写入 FetchContent 或按 FetchFailures 抛出异常</summary>
/// <param name="client">源节点客户端</param>
/// <param name="url">下载地址</param>
/// <param name="fileName">目标文件完整路径</param>
/// <param name="expectedHash">预期哈希</param>
/// <param name="cancellationToken">取消通知</param>
protected override async Task DownloadFileAsync(ApiHttpClient client, String url, String fileName, String? expectedHash, CancellationToken cancellationToken)
{
var count = Interlocked.Increment(ref FetchCount);
if (FetchDelay > TimeSpan.Zero) await Task.Delay(FetchDelay, cancellationToken).ConfigureAwait(false);
if (count <= FetchFailures) throw new IOException("Simulated download failure.");
fileName.EnsureDirectory(true);
File.WriteAllBytes(fileName, FetchContent.GetBytes());
}
}
/// <summary>简单服务提供者,按类型返回注册的实例</summary>
internal class FakeServiceProvider : IServiceProvider
{
private readonly Dictionary<Type, Object?> _dic = [];
public void Add(Type type, Object? value) => _dic[type] = value;
public Object? GetService(Type serviceType) => _dic.TryGetValue(serviceType, out var value) ? value : null;
}
/// <summary>分布式文件存储测试。覆盖事件总线降级路径(Redis → 星尘 → MemoryCache)</summary>
public class DefaultFileStorageTests
{
[Fact]
public async Task InitializeAsync_NoProvider_NoThrow()
{
// 无服务提供者时不抛异常,事件总线保持为空
using var storage = new TestFileStorage();
await storage.InitializeAsync();
Assert.Null(storage.NewFileBus);
}
[Fact]
public async Task InitializeAsync_WithAppClient_UsesStarEventBus()
{
// IRegistry 返回 AppClient 时,应走到星尘事件总线分支(修复前为死代码)
var provider = new FakeServiceProvider();
// ICacheProvider 存在(非Redis),用于触发后续降级判断
var cacheProvider = new Mock<ICacheProvider>();
cacheProvider.SetupGet(e => e.Cache).Returns(new MemoryCache());
cacheProvider.SetupGet(e => e.InnerCache).Returns(new MemoryCache());
provider.Add(typeof(ICacheProvider), cacheProvider.Object);
var client = new AppClient("http://localhost");
provider.Add(typeof(IRegistry), client);
using var storage = new TestFileStorage { Name = "Test", ServiceProvider = provider };
await storage.InitializeAsync();
Assert.NotNull(storage.NewFileBus);
Assert.NotNull(storage.FileRequestBus);
}
[Fact]
public async Task InitializeAsync_WithoutRegistry_FallbackMemoryCache()
{
// 无 IRegistry 时回退 MemoryCache 分支,事件总线应被创建
var provider = new FakeServiceProvider();
var cacheProvider = new Mock<ICacheProvider>();
cacheProvider.SetupGet(e => e.Cache).Returns(new MemoryCache());
cacheProvider.SetupGet(e => e.InnerCache).Returns(new MemoryCache());
provider.Add(typeof(ICacheProvider), cacheProvider.Object);
using var storage = new TestFileStorage { Name = "Test", ServiceProvider = provider };
await storage.InitializeAsync();
Assert.NotNull(storage.NewFileBus);
Assert.NotNull(storage.FileRequestBus);
}
#region CheckLocalFile 本地文件校验
private static String NewDir() => Path.Combine(Path.GetTempPath(), "StarStorage_" + Guid.NewGuid().ToString("N"));
[Fact]
[DisplayName("CheckLocalFile_文件不存在_返回False")]
public void CheckLocalFile_MissingFile_ReturnsFalse()
{
using var storage = new TestFileStorage { RootPath = NewDir() };
Assert.False(storage.CheckLocalFile("App/x.zip", null));
}
[Fact]
[DisplayName("CheckLocalFile_哈希为空且文件存在_返回True")]
public void CheckLocalFile_NoHash_FileExists_ReturnsTrue()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
File.WriteAllText(Path.Combine(dir, "a.txt"), "hello");
using var storage = new TestFileStorage { RootPath = dir };
Assert.True(storage.CheckLocalFile("a.txt", null));
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("CheckLocalFile_哈希匹配_返回True")]
public void CheckLocalFile_HashMatch_ReturnsTrue()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var path = Path.Combine(dir, "a.txt");
File.WriteAllText(path, "hello");
var hash = path.AsFile().MD5().ToHex();
using var storage = new TestFileStorage { RootPath = dir };
Assert.True(storage.CheckLocalFile("a.txt", hash));
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("CheckLocalFile_哈希不匹配_返回False")]
public void CheckLocalFile_HashMismatch_ReturnsFalse()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
File.WriteAllText(Path.Combine(dir, "a.txt"), "hello");
using var storage = new TestFileStorage { RootPath = dir };
Assert.False(storage.CheckLocalFile("a.txt", "00000000000000000000000000000000"));
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("CheckLocalFile_文件被独占占用_容错返回False")]
public void CheckLocalFile_FileLocked_ReturnsFalse()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var path = Path.Combine(dir, "a.txt");
File.WriteAllText(path, "hello");
var hash = path.AsFile().MD5().ToHex();
// 以排他模式打开文件,模拟文件正被其他进程写入/替换
using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
using var storage = new TestFileStorage { RootPath = dir };
Assert.False(storage.CheckLocalFile("a.txt", hash));
}
}
finally
{
Directory.Delete(dir, true);
}
}
#endregion
#region 并发下载与跨进程锁
[Fact]
[DisplayName("并发NewFile_同一文件_只下载一次")]
public async Task OnNewFileInfoAsync_ConcurrentMessages_DownloadsOnce()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var content = "hello concurrent";
var hash = content.GetBytes().MD5().ToHex();
using var storage = new TestFileStorage
{
RootPath = dir,
NodeName = "nodeB",
FetchContent = content,
FetchDelay = TimeSpan.FromMilliseconds(200),
};
var info = new NewFileInfo
{
Id = 1,
Name = "a.txt",
Path = "a.txt",
Hash = hash,
SourceNode = "nodeA",
InternalAddress = "http://127.0.0.1:1",
ExternalAddress = "http://127.0.0.1:1",
};
var tasks = Enumerable.Range(0, 10).Select(_ => storage.OnNewFileInfoAsync(info)).ToArray();
await Task.WhenAll(tasks);
Assert.Equal(1, storage.FetchCount);
Assert.True(storage.CheckLocalFile("a.txt", hash));
Assert.Equal(content, File.ReadAllText(Path.Combine(dir, "a.txt")));
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("同机两个进程_同一文件_只下载一次")]
public async Task OnNewFileInfoAsync_TwoStoragesSameRoot_DownloadsOnce()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var content = "hello cross process";
var hash = content.GetBytes().MD5().ToHex();
using var web = new TestFileStorage
{
RootPath = dir,
NodeName = "B-StarWeb",
FetchContent = content,
FetchDelay = TimeSpan.FromMilliseconds(300),
FileLockTimeout = 5_000,
};
using var server = new TestFileStorage
{
RootPath = dir,
NodeName = "B-StarServer",
FetchContent = content,
FetchDelay = TimeSpan.FromMilliseconds(300),
FileLockTimeout = 5_000,
};
var info = new NewFileInfo
{
Id = 1,
Name = "a.txt",
Path = "a.txt",
Hash = hash,
SourceNode = "A-StarWeb",
InternalAddress = "http://127.0.0.1:1",
ExternalAddress = "http://127.0.0.1:1",
};
await Task.WhenAll(web.OnNewFileInfoAsync(info), server.OnNewFileInfoAsync(info));
Assert.Equal(1, web.FetchCount + server.FetchCount);
Assert.True(web.CheckLocalFile("a.txt", hash));
Assert.True(server.CheckLocalFile("a.txt", hash));
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("下载失败后_下一条消息可以重试")]
public async Task OnNewFileInfoAsync_FetchFails_NextMessageRetries()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var content = "hello retry";
var hash = content.GetBytes().MD5().ToHex();
using var storage = new TestFileStorage
{
RootPath = dir,
NodeName = "nodeB",
FetchContent = content,
FetchDelay = TimeSpan.Zero,
FetchFailures = 1,
};
var info = new NewFileInfo
{
Id = 1,
Name = "a.txt",
Path = "a.txt",
Hash = hash,
SourceNode = "nodeA",
InternalAddress = "http://127.0.0.1:1",
ExternalAddress = "http://127.0.0.1:1",
};
await storage.OnNewFileInfoAsync(info);
Assert.False(storage.CheckLocalFile("a.txt", hash));
await storage.OnNewFileInfoAsync(info);
Assert.Equal(2, storage.FetchCount);
Assert.True(storage.CheckLocalFile("a.txt", hash));
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("本地已有正确文件_不重复下载")]
public async Task OnNewFileInfoAsync_FileAlreadyExists_DoesNotFetch()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var content = "hello exists";
var path = Path.Combine(dir, "a.txt");
File.WriteAllBytes(path, content.GetBytes());
var hash = path.AsFile().MD5().ToHex();
using var storage = new TestFileStorage
{
RootPath = dir,
NodeName = "nodeB",
FetchContent = content,
};
var info = new NewFileInfo
{
Id = 1,
Name = "a.txt",
Path = "a.txt",
Hash = hash,
SourceNode = "nodeA",
};
await storage.OnNewFileInfoAsync(info);
Assert.Equal(0, storage.FetchCount);
Assert.True(storage.CheckLocalFile("a.txt", hash));
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("文件锁_被占用时等待超时")]
public async Task AcquireFileLockAsync_Locked_WaitsAndTimesOut()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var fileName = Path.Combine(dir, "a.txt");
using var storage = new TestFileStorage { RootPath = dir, FileLockTimeout = 300 };
using var first = await storage.AcquireFileLockAsync(fileName, null);
Assert.NotNull(first);
var sw = Stopwatch.StartNew();
var second = await storage.AcquireFileLockAsync(fileName, null);
sw.Stop();
Assert.Null(second);
Assert.True(sw.ElapsedMilliseconds >= 250, $"Elapsed={sw.ElapsedMilliseconds}ms");
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("文件锁_释放后可以重新获取")]
public async Task AcquireFileLockAsync_Released_CanAcquire()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var fileName = Path.Combine(dir, "a.txt");
using var storage = new TestFileStorage { RootPath = dir };
var first = await storage.AcquireFileLockAsync(fileName, null);
Assert.NotNull(first);
first!.Dispose();
var second = await storage.AcquireFileLockAsync(fileName, null);
Assert.NotNull(second);
second!.Dispose();
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
[DisplayName("文件锁_目标文件已存在_直接返回")]
public async Task AcquireFileLockAsync_FileExists_ReturnsNull()
{
var dir = NewDir();
Directory.CreateDirectory(dir);
try
{
var content = "hello lock";
var fileName = Path.Combine(dir, "a.txt");
File.WriteAllBytes(fileName, content.GetBytes());
var hash = fileName.AsFile().MD5().ToHex();
using var storage = new TestFileStorage { RootPath = dir };
var lockFile = await storage.AcquireFileLockAsync(fileName, hash);
Assert.Null(lockFile);
}
finally
{
Directory.Delete(dir, true);
}
}
#endregion
}
|