using System.Globalization; using System.Net; using System.Text; using Khaemhat.Application.Audit; using Khaemhat.Application.Files; using Khaemhat.Application.Localization; using Khaemhat.Application.Security; using Khaemhat.Core.Security; using Khaemhat.Web.Hosting; using Khaemhat.Web.Tests.Hosting; using Khaemhat.Web.Ui; using Microsoft.Extensions.DependencyInjection; namespace Khaemhat.Web.Tests.Files; /// What the interface of the attachments needs (issue #34, mockup 024-025): previews, sizes, texts, history, addresses. [TestClass] public sealed class AttachmentUiTests { private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); [TestMethod] public void Csv_Preview_ReadsSeparatorQuotesAndLimits() { var rows = FilePreview.Csv("Codice;Descrizione;Importo\r\nA1;\"Vite; \"\"zincata\"\"\";1,25\r\nA2;\"riga\nsu due\";3\n", out var truncated); Assert.IsFalse(truncated); Assert.HasCount(3, rows); CollectionAssert.AreEqual(new[] { "Codice", "Descrizione", "Importo" }, rows[0].ToList()); CollectionAssert.AreEqual(new[] { "A1", "Vite; \"zincata\"", "1,25" }, rows[1].ToList()); Assert.AreEqual("riga\nsu due", rows[2][1]); CollectionAssert.AreEqual(new[] { "a", "b" }, FilePreview.Csv("a,b", out _)[0].ToList()); var many = FilePreview.Csv(string.Concat(Enumerable.Repeat("x;y\n", FilePreview.MaxRows + 5)), out var cut); Assert.IsTrue(cut); Assert.HasCount(FilePreview.MaxRows, many); } [TestMethod] public async Task Xlsx_Preview_ReadsWhatTheGeneratorWrites() { var generator = new DemoXlsxGenerator(); using var content = new MemoryStream(); await generator.GenerateAsync(new FileGenerationContext(Root, "DEMO", DemoDocument.Entity, 3, Italian, new DateTime(2026, 11, 11, 10, 0, 0, DateTimeKind.Utc)), content, CancellationToken.None); content.Position = 0; var preview = await FilePreview.ReadAsync(AttachmentPreview.Xlsx, content, Italian); Assert.IsNotNull(preview.Rows); var cells = preview.Rows.SelectMany(r => r).ToList(); foreach (var header in DemoDocument.Headers) { CollectionAssert.Contains(cells, header); } CollectionAssert.Contains(cells, "PROVA-001"); Assert.IsTrue(preview.Rows.Any(r => r.Contains("PROVA-003") && r.Any(c => c.Contains("25,5", StringComparison.Ordinal))), "Numbers in Italian form."); } [TestMethod] public async Task Text_Preview_IsCut_AndBrokenFilesSayNothing() { using var big = new MemoryStream(Encoding.UTF8.GetBytes(new string('x', FilePreview.MaxChars + 10))); var text = await FilePreview.ReadAsync(AttachmentPreview.Xml, big, Italian); Assert.IsTrue(text.Truncated); Assert.AreEqual(FilePreview.MaxChars, text.Text!.Length); using var broken = new MemoryStream(Encoding.UTF8.GetBytes("not a zip")); var xlsx = await FilePreview.ReadAsync(AttachmentPreview.Xlsx, broken, Italian); Assert.IsNull(xlsx.Rows); Assert.IsNull(xlsx.Text); } [TestMethod] [DataRow(0L, "0 B")] [DataRow(840L, "840 B")] [DataRow(1536L, "1,5 KB")] [DataRow(188_416L, "184 KB")] [DataRow(26_214_400L, "25 MB")] public void Sizes_AreReadable(long bytes, string expected) => Assert.AreEqual(expected, FileSizes.Format(bytes, Italian)); [TestMethod] public void EveryErrorAndGenerator_HasItsText() { var texts = JsonTextProvider.FromAssembly(typeof(FileEndpoints).Assembly, Italian); string[] codes = [ AttachmentService.NotFoundError, AttachmentService.LockedError, AttachmentService.TooLargeError, AttachmentService.QuotaError, AttachmentService.RejectedError, AttachmentService.InvalidOwnerError, AttachmentService.EmptyError, FileGenerationService.UnknownGeneratorError, ]; IFileGenerator[] generators = [new DemoPdfGenerator(), new DemoCsvGenerator(), new DemoXlsxGenerator()]; var missing = codes.Concat(generators.Select(g => g.TitleKey)).Where(k => !texts.Contains(k)).ToList(); Assert.IsEmpty(missing, string.Join(", ", missing)); } [TestMethod] public void Addresses_OpenOnlySafeTypesInTheBrowser() { Assert.AreEqual("files/42", FileEndpoints.View(42)); Assert.AreEqual("files/42?download=1", FileEndpoints.Download(42)); Assert.AreEqual("files/zip?entity=demo.document&id=7", FileEndpoints.Zip("demo.document", 7)); Assert.AreEqual("files/generate?entity=demo.document&id=7&generator=demo.test-pdf&download=1", FileEndpoints.Generated("demo.document", 7, "demo.test-pdf", true)); Assert.IsTrue(FileEndpoints.OpensInBrowser(MediaTypes.Pdf)); Assert.IsTrue(FileEndpoints.OpensInBrowser("image/png")); Assert.IsFalse(FileEndpoints.OpensInBrowser("image/svg+xml"), "SVG can carry scripts."); Assert.IsFalse(FileEndpoints.OpensInBrowser("text/html")); Assert.IsFalse(FileEndpoints.OpensInBrowser(MediaTypes.Xml)); } [TestMethod] public async Task Files_NeedASignedInUser_AndTheHistoryShowsTheUpload() { var (app, address, company) = await TestInstance.StartAsync(CancellationToken.None); await using (app) { var attachments = app.Services.GetRequiredService(); var added = await attachments.UploadAsync(Root, company, DemoDocument.Entity, 5, "nota.txt", "text/plain", new MemoryStream(Encoding.UTF8.GetBytes("ciao"))); using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = address }; foreach (var path in new[] { "/" + FileEndpoints.View(added.Id), "/" + FileEndpoints.Zip(DemoDocument.Entity, 5), "/" + FileEndpoints.Generated(DemoDocument.Entity, 5, DemoPdfGenerator.GeneratorCode) }) { using var response = await client.GetAsync(new Uri(path, UriKind.Relative)); Assert.AreNotEqual(HttpStatusCode.OK, response.StatusCode, path); Assert.AreNotEqual("ciao", await response.Content.ReadAsStringAsync(), path); } var history = await app.Services.GetRequiredService().HistoryAsync( Root, company, "Attachment", added.Id.ToString(CultureInfo.InvariantCulture), AttachmentService.ReadPermission); var insert = history.Single(); Assert.AreEqual(AuditAction.Insert, insert.Action); Assert.AreEqual(TestInstance.SuperUser, insert.UserName); Assert.IsTrue(insert.Changes.Any(c => c.Field == "Name" && c.Before is null && c.After == "nota.txt")); var stranger = new Actor("anna", UserLevel.Standard, null, 999, "ALTRA"); await Assert.ThrowsExactlyAsync(() => app.Services.GetRequiredService().HistoryAsync( stranger, company, "Attachment", added.Id.ToString(CultureInfo.InvariantCulture), AttachmentService.ReadPermission)); await app.StopAsync(); } } }