using System.IO.Compression; using System.Text; using Khaemhat.Infrastructure.Files; namespace Khaemhat.Infrastructure.Tests.Files; /// The XLSX reader of the guided import (issue #44): what the writer produces comes back as text. [TestClass] public sealed class XlsxReaderTests { [TestMethod] [DataRow(false)] [DataRow(true)] public async Task ReadsBackWhatTheWriterWrites(bool sharedStrings) { using var buffer = new MemoryStream(); await using (var writer = await XlsxWriter.CreateAsync(buffer, new XlsxOptions { UseSharedStrings = sharedStrings }, leaveOpen: true)) { await writer.StartSheetAsync("clienti", [new("codice"), new("prezzo"), new("dal"), new("attivo"), new("note")]); await writer.WriteRowAsync(["C001", 1234.5m, new DateOnly(2026, 11, 12), true, null]); await writer.WriteRowAsync([null, null, null, null, null]); await writer.WriteRowAsync(["C002", -3m, null, false, "Via \"Roma\" & co. <1>"]); await writer.CompleteAsync(); } buffer.Position = 0; var rows = await XlsxReader.ReadAsync(buffer); Assert.HasCount(3, rows, "Header and two rows: the empty row is skipped."); CollectionAssert.AreEqual(new[] { "codice", "prezzo", "dal", "attivo", "note" }, rows[0].ToArray()); Assert.AreEqual("C001", rows[1][0]); Assert.AreEqual("1234.5", rows[1][1], "Numbers come in invariant notation."); Assert.AreEqual("2026-11-12", rows[1][2], "Date-styled numbers come back as ISO dates."); Assert.AreEqual("true", rows[1][3]); Assert.AreEqual("-3", rows[2][1]); Assert.AreEqual(string.Empty, rows[2][2], "A gap between cells is an empty cell."); Assert.AreEqual("false", rows[2][3]); Assert.AreEqual("Via \"Roma\" & co. <1>", rows[2][4]); } [TestMethod] public async Task NotAWorkbook_IsRefused() { using var text = new MemoryStream(Encoding.UTF8.GetBytes("codice;descrizione\nA;B\n")); await Assert.ThrowsExactlyAsync(() => XlsxReader.ReadAsync(text)); using var zip = new MemoryStream(); using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true)) { archive.CreateEntry("readme.txt"); } zip.Position = 0; await Assert.ThrowsExactlyAsync(() => XlsxReader.ReadAsync(zip)); } [TestMethod] [DataRow("A1", 0)] [DataRow("C7", 2)] [DataRow("Z10", 25)] [DataRow("AA1", 26)] [DataRow("AB12", 27)] public void ColumnOf_ReadsTheLetters(string reference, int column) => Assert.AreEqual(column, XlsxReader.ColumnOf(reference)); }