using System; using System.IO; using System.Text; using System.Threading.Tasks; using GsDChat.Server.Configuration; using GsDChat.Server.Data; using GsDChat.Server.Services; using Xunit; namespace GsDChat.Tests; public class FileStorageServiceTests : IDisposable { private readonly string _testDir; private readonly ChatDatabase _db; private readonly ServerOptions _options; private readonly FileStorageService _fileService; public FileStorageServiceTests() { _testDir = Path.Combine(Path.GetTempPath(), "gsdchat_file_test_" + Guid.NewGuid().ToString("N")); _db = new ChatDatabase(_testDir); _db.InitializeAsync().GetAwaiter().GetResult(); _options = new ServerOptions { DataDirectory = _testDir, MaxFileSizeMb = 5 }; _fileService = new FileStorageService(_db, _options); } public void Dispose() { _db.Dispose(); try { if (Directory.Exists(_testDir)) { Directory.Delete(_testDir, true); } } catch { } } [Fact] public async Task StoreAndReadFile_ShouldPreserveExactContentAndComputeSha256() { var channels = await _db.GetChannelsAsync(); var general = channels[0]; string fileContent = "Hello from GsDChat test file storage! Secure and modular."; byte[] fileBytes = Encoding.UTF8.GetBytes(fileContent); using var memoryStream = new MemoryStream(fileBytes); var record = await _fileService.StoreFileAsync( general.Id, "uploader-1", "Tester", "test_note.txt", "text/plain", memoryStream, fileBytes.Length ); Assert.NotNull(record); Assert.Equal("test_note.txt", record.OriginalFileName); Assert.Equal(fileBytes.Length, record.FileSizeBytes); Assert.False(string.IsNullOrWhiteSpace(record.Sha256Checksum)); // Read file back var fetchedRecord = await _fileService.GetFileRecordAsync(record.Id); Assert.NotNull(fetchedRecord); Assert.Equal(record.Sha256Checksum, fetchedRecord.Sha256Checksum); using var stream = _fileService.OpenFileStream(fetchedRecord); Assert.NotNull(stream); using var reader = new StreamReader(stream, Encoding.UTF8); string readBack = await reader.ReadToEndAsync(); Assert.Equal(fileContent, readBack); } }