Files
Khaemhat/tests/Khaemhat.Infrastructure.Tests/Mail/MimeAndImapTests.cs
T
Alby96andClaude Opus 5.5 709bb13532 feat: FatturaPA writer, validator, SDI receipts and transport channels (#74 #75 #76 #77)
The Italian pack can now produce and check the e-invoice and talk to the SDI:
- FatturaPaWriter writes FPR12/FPA12 v1.2 with SDI file naming; FatturaPaValidator
  checks it against an embedded schema and the AdE semantic rules (official codes).
- SdiReceiptReader reads RC, NS, MC, NE, DT, AT, MT and SE notifications.
- The incoming-invoice model becomes the shared EInvoice* model, read and written.
- In-house ImapClient and MimeParser (no external libraries) back the PEC channel;
  SdICoop (SOAP/MTOM with client certificate) and two generic REST intermediaries
  sit behind the same IEInvoiceTransport contract, with fake-server tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:51:31 +01:00

152 lines
7.6 KiB
C#

using System.Text;
using Khaemhat.Infrastructure.Mail;
namespace Khaemhat.Infrastructure.Tests.Mail;
[TestClass]
public sealed class MimeParserTests
{
[TestMethod]
public void Certified_mail_gives_the_files_of_the_enclosed_message()
{
var receipt = Encoding.UTF8.GetBytes("<RicevutaConsegna/>");
var message = MimeParser.Parse(PecSamples.Envelope("sdi07@pec.fatturapa.it", "Consegna", ("IT01234567897_00001_RC_001.xml", receipt)));
Assert.AreEqual("multipart/signed", message.MediaType);
Assert.AreEqual("POSTA CERTIFICATA: Consegna", message.Header("Subject"));
var envelope = message.Parts[0];
var original = envelope.Parts.Single(p => p.MediaType == "message/rfc822");
Assert.AreEqual("postacert.eml", original.FileName);
Assert.IsNotNull(original.Enclosed);
Assert.AreEqual("sdi07@pec.fatturapa.it", original.Enclosed.Header("from"));
var file = original.Enclosed.Attachments().Single();
Assert.AreEqual("IT01234567897_00001_RC_001.xml", file.FileName);
CollectionAssert.AreEqual(receipt, file.Body);
var all = message.Attachments().Select(a => a.FileName).ToList();
CollectionAssert.AreEqual(new[] { "daticert.xml", "IT01234567897_00001_RC_001.xml", "smime.p7s" }, all);
StringAssert.Contains(envelope.Parts[0].Text(), "il messaggio originale è allegato");
}
[TestMethod]
public void Encoded_words_are_decoded_and_joined()
{
Assert.AreEqual("Fattura n° 12", MimeParser.DecodeHeader("=?utf-8?Q?Fattura_n=C2=B0?= 12"));
Assert.AreEqual("perché sì", MimeParser.DecodeHeader("=?iso-8859-1?Q?perch=E9?= =?iso-8859-1?Q?_s=EC?="));
Assert.AreEqual("città", MimeParser.DecodeHeader("=?UTF-8?B?Y2l0dMOg?="));
Assert.AreEqual("plain =? text", MimeParser.DecodeHeader("plain =? text"));
}
[TestMethod]
public void File_names_follow_rfc_2231()
{
var message = Encoding.ASCII.GetBytes(
"Content-Type: multipart/mixed; boundary=b\r\n\r\n" +
"--b\r\nContent-Type: application/xml\r\nContent-Disposition: attachment; filename*=utf-8''fattura%20citt%C3%A0.xml\r\n\r\n<a/>\r\n" +
"--b\r\nContent-Type: application/xml\r\nContent-Disposition: attachment;\r\n filename*0=\"IT0123_\"; filename*1=\"00001.xml\"\r\n\r\n<b/>\r\n" +
"--b\r\nContent-Type: application/xml; name=\"=?utf-8?Q?n=C2=B0.xml?=\"\r\n\r\n<c/>\r\n" +
"--b--\r\n");
var names = MimeParser.Parse(message).Attachments().Select(a => a.FileName).ToList();
CollectionAssert.AreEqual(new[] { "fattura città.xml", "IT0123_00001.xml", "n°.xml" }, names);
}
[TestMethod]
public void Quoted_printable_and_broken_input_do_not_throw()
{
CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("a=b c"), MimeParser.QuotedPrintable(Encoding.ASCII.GetBytes("a=3Db =\r\nc")));
CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("ab"), MimeParser.Base64(Encoding.ASCII.GetBytes("YW\r\nI=")));
var unclosed = MimeParser.Parse(Encoding.ASCII.GetBytes("Content-Type: multipart/mixed; boundary=x\r\n\r\n--x\r\nContent-Type: text/plain\r\n\r\nhello"));
Assert.AreEqual("hello", unclosed.Parts.Single().Text());
var noHeaders = MimeParser.Parse(Encoding.ASCII.GetBytes("just text"));
Assert.AreEqual("text/plain", noHeaders.MediaType);
}
}
[TestClass]
public sealed class ImapClientTests
{
private static readonly byte[] First = PecSamples.Envelope("sdi01@pec.fatturapa.it", "Uno", ("IT01234567897_00001_RC_001.xml", [1]));
private static readonly byte[] Second = PecSamples.Acceptance("Due");
[TestMethod]
public async Task Search_fetch_flag_and_move()
{
await using var server = new FakeImapServer("fatture@pec.example.it", "segreto", First, Second);
var token = TestContext.CancellationToken;
await using var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "fatture@pec.example.it", "segreto"), token);
await imap.LoginAsync("fatture@pec.example.it", "segreto", token);
Assert.IsTrue(imap.Capabilities.Contains("MOVE"));
Assert.AreEqual(2, await imap.SelectAsync("INBOX", token));
var uids = await imap.SearchAsync("UNSEEN FROM " + ImapClient.Quote("fatturapa.it"), token);
Assert.AreEqual(1, uids.Count);
var message = await imap.FetchAsync(uids[0], token);
Assert.IsNotNull(message);
CollectionAssert.AreEqual(First, message.Content);
Assert.IsFalse(server.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen"), "BODY.PEEK must not mark the message.");
await imap.AddFlagsAsync(uids[0], @"\Seen", token);
Assert.IsTrue(server.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen"));
Assert.AreEqual(0, (await imap.SearchAsync("UNSEEN FROM \"fatturapa.it\"", token)).Count);
await imap.MoveAsync(uids[0], "Khaemhat/SDI", token);
Assert.AreEqual(1, server.Mailboxes["Khaemhat/SDI"].Count);
Assert.AreEqual(1, server.Mailboxes["INBOX"].Count);
Assert.IsNull(await imap.FetchAsync(uids[0], token));
await imap.LogoutAsync(token);
}
[TestMethod]
public async Task Without_move_the_message_is_copied_and_expunged()
{
await using var server = new FakeImapServer("u", "p", First) { SupportsMove = false };
server.Mailboxes["Archivio"] = [];
var token = TestContext.CancellationToken;
await using var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "p"), token);
await imap.LoginAsync("u", "p", token);
await imap.SelectAsync("INBOX", token);
await imap.MoveAsync((await imap.SearchAsync("ALL", token))[0], "Archivio", token);
Assert.AreEqual(0, server.Mailboxes["INBOX"].Count);
Assert.AreEqual(1, server.Mailboxes["Archivio"].Count);
Assert.IsTrue(server.Commands.Any(c => c.Contains("UID COPY", StringComparison.Ordinal)));
Assert.IsTrue(server.Commands.Any(c => c.EndsWith("EXPUNGE", StringComparison.Ordinal)));
}
[TestMethod]
public async Task Password_with_accents_goes_as_a_literal_and_wrong_password_fails()
{
await using var server = new FakeImapServer("u", "pàssword");
var token = TestContext.CancellationToken;
await using (var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "pàssword"), token))
{
await imap.LoginAsync("u", "pàssword", token);
}
Assert.IsTrue(server.Commands.Any(c => c.StartsWith("K0002 LOGIN \"u\" {", StringComparison.Ordinal)));
await using var wrong = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "x"), token);
var error = await Assert.ThrowsExactlyAsync<MailException>(() => wrong.LoginAsync("u", "x", token));
StringAssert.Contains(error.Message, "LOGIN ***");
Assert.IsFalse(error.Message.Contains("\"x\"", StringComparison.Ordinal), "The password must not appear in the error.");
}
[TestMethod]
public async Task Unreachable_server_gives_a_mail_exception()
{
var settings = new ImapSettings("127.0.0.1", 1, false, "u", "p");
await Assert.ThrowsExactlyAsync<MailException>(() => ImapClient.ConnectAsync(settings, TestContext.CancellationToken));
Assert.AreEqual("127.0.0.1:1", settings.ToString());
Assert.AreEqual("1-Nov-2026", ImapClient.SearchDate(new DateOnly(2026, 11, 1)));
Assert.ThrowsExactly<MailException>(() => ImapClient.Quote("città"));
}
public TestContext TestContext { get; set; } = null!;
}