Files
slp-modular-cms/src/SlpModularCms.Modules.Contact.Tests/ContactMailTests.cs
T
2026-11-15 20:57:17 +01:00

462 lines
19 KiB
C#

using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using SlpModularCms.Core.Email;
using SlpModularCms.Core.SiteSettings;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
public class ContactMailOptionsTests
{
[Theory]
[InlineData(1, 5)]
[InlineData(2, 15)]
[InlineData(3, 60)]
[InlineData(4, 360)]
[InlineData(5, 1440)]
[InlineData(9, 1440)]
public void TheBackoff_IsFiveMinutesFifteenMinutesOneHourSixHoursTwentyFourHours(int attempts, int minutes)
=> new ContactMailOptions().BackoffAfter(attempts).Should().Be(TimeSpan.FromMinutes(minutes));
[Fact]
public void TheDefaults_AreSixAttempts()
=> new ContactMailOptions().MaxAttempts.Should().Be(6);
}
public class ContactMailSenderTests
{
private const string Visitor = "jan@example.nl";
private sealed class Rig
{
public IEmailSender Email { get; } = Substitute.For<IEmailSender>();
public IMailAvailability Availability { get; } = Substitute.For<IMailAvailability>();
public ContactOptions Contact { get; } = new() { Enabled = true, RecipientEmail = "owner@example.org" };
public CapturingLoggerProvider Logs { get; } = new();
public OutgoingMail? Sent;
private readonly ContactDbContext _db = new(new DbContextOptionsBuilder<ContactDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
/// <summary>The real settings service on an in-memory database: the administrator's setting and the environment.</summary>
public IContactSettingsService ContactSettings => new ContactSettingsService(
new ContactRepository(_db), new ContactSettingsCache(TimeProvider.System), Options.Create(Contact),
TimeProvider.System, Substitute.For<IContactMailSignal>());
public Rig()
{
Availability.IsEnabled.Returns(true);
Email.SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>()).Returns(call =>
{
Sent = call.Arg<OutgoingMail>();
return MailSendResult.Ok;
});
}
public ContactMailSender Build(string language = "nl")
{
var languages = Substitute.For<ILanguageResolver>();
languages.Resolve(Arg.Any<string?>()).Returns(language);
var settings = Substitute.For<ISiteSettingsService>();
settings.GetEffectiveSenderAsync(Arg.Any<CancellationToken>()).Returns(("noreply@example.org", "De Site"));
return new ContactMailSender(
Email, new MailTemplateRenderer(SlpModularCms.Core.Texts.TextCatalog.CreateDefault()), languages, settings, ContactSettings, Availability,
Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }),
Options.Create(Contact), LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger<ContactMailSender>());
}
}
private static ContactMessage Message(string name = "Jan Jansen", string subject = "website", string body = "Hallo\nwereld")
=> new() { Id = Guid.NewGuid(), SiteId = "s", Name = name, Email = Visitor, Subject = subject, Message = body };
[Fact]
public async Task ASend_GoesToTheRecipient_FromTheSiteSender_WithTheVisitorAsReplyTo()
{
var rig = new Rig();
var result = await rig.Build().SendAsync(Message(), CancellationToken.None);
result.Outcome.Should().Be(ContactMailOutcome.Sent);
rig.Sent!.ToAddress.Should().Be("owner@example.org");
rig.Sent.FromAddress.Should().Be("noreply@example.org");
rig.Sent.ReplyToAddress.Should().Be(Visitor);
rig.Sent.ReplyToName.Should().Be("Jan Jansen");
}
[Fact]
public async Task TheSubject_NeverContainsAnythingTheVisitorTyped()
{
var rig = new Rig();
await rig.Build().SendAsync(Message(name: "ZXQ-Name", subject: "ZXQ-Subject\r\nBcc: x@y.z", body: "ZXQ-Body"), CancellationToken.None);
rig.Sent!.Subject.Should().NotContain("ZXQ").And.NotContain("\r").And.NotContain("\n");
rig.Sent.Subject.Should().Be("Nieuw bericht via De Site");
}
[Theory]
[InlineData("nl", "Naam:", "E-mailadres:", "Onderwerp:", "Bericht:")]
[InlineData("en", "Name:", "E-mail address:", "Subject:", "Message:")]
public async Task TheDetailLabels_AreTheOnesOfTheMailLanguage(string language, string name, string email, string subject, string message)
{
var rig = new Rig();
await rig.Build(language).SendAsync(Message(), CancellationToken.None);
var lines = rig.Sent!.TextBody!.Replace("\r\n", "\n").Split('\n');
lines.Should().ContainInOrder(name, email, subject, message);
foreach (var label in new[] { name, email, subject, message })
{
rig.Sent.HtmlBody.Should().Contain(">" + label.TrimEnd(':') + "<");
}
}
[Fact]
public async Task TheBody_EncodesHtml_AndKeepsLineBreaks_AndHasATextPart()
{
var rig = new Rig();
await rig.Build().SendAsync(Message(body: "<script>alert(1)</script>\nregel2"), CancellationToken.None);
rig.Sent!.HtmlBody.Should().NotContain("<script>").And.Contain("&lt;script&gt;").And.Contain("<br");
rig.Sent.TextBody.Should().Contain("regel2").And.Contain("Naam:");
}
[Fact]
public async Task ASubjectLabelWithSpecialCharacters_IsEncodedInTheBody_AndNeverReachesTheSubjectOrAHeader()
{
var rig = new Rig();
const string label = "Fotoshoot & <b>\"bruiloft\"</b> 'zomer'";
await rig.Build().SendAsync(Message(subject: label), CancellationToken.None);
rig.Sent!.Subject.Should().Be("Nieuw bericht via De Site");
rig.Sent.HtmlBody.Should().Contain("Fotoshoot &amp; &lt;b&gt;").And.NotContain("<b>\"bruiloft\"");
rig.Sent.TextBody.Should().Contain(" " + label);
rig.Sent.ReplyToAddress.Should().Be(Visitor);
}
[Fact]
public async Task English_UsesEnglishLabelsAndSubject()
{
var rig = new Rig();
await rig.Build("en").SendAsync(Message(), CancellationToken.None);
rig.Sent!.Subject.Should().Be("New message via De Site");
rig.Sent.TextBody.Should().Contain("Name:").And.Contain("Message:");
}
[Fact]
public async Task AControlCharacterInTheVisitorName_NeverReachesAHeader()
{
var rig = new Rig();
await rig.Build().SendAsync(Message(name: "Jan\r\nBcc: evil@example.com"), CancellationToken.None);
rig.Sent!.ReplyToName.Should().BeNull("an invalid display name is not used; the address alone is");
rig.Sent.ReplyToAddress.Should().Be(Visitor);
}
[Fact]
public async Task AFailure_IsReturnedAsItsShortCode_AndLogsNoPersonalData()
{
var rig = new Rig();
rig.Email.SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>()).Returns(MailSendResult.Fail(MailSendResult.AuthFailed));
var result = await rig.Build().SendAsync(Message(name: "ZXQ-Name", body: "ZXQ-Body"), CancellationToken.None);
result.Should().Be(new ContactMailResult(ContactMailOutcome.Failed, "auth_failed"));
rig.Logs.Messages.Should().NotContain(m => m.Contains("ZXQ") || m.Contains(Visitor) || m.Contains("owner@example.org"));
}
[Fact]
public async Task AnExceptionFromTheSender_BecomesUnknown_LoggedByTypeOnly()
{
var rig = new Rig();
rig.Email.SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>())
.ThrowsAsync(new InvalidOperationException($"cannot deliver to {Visitor}"));
var result = await rig.Build().SendAsync(Message(), CancellationToken.None);
result.Should().Be(new ContactMailResult(ContactMailOutcome.Failed, "unknown"));
rig.Logs.Messages.Should().NotContain(m => m.Contains(Visitor));
rig.Logs.Messages.Should().Contain(m => m.Contains(nameof(InvalidOperationException)));
}
[Fact]
public async Task WhenMailIsOff_NothingIsSent_AndTheReasonIsDisabled()
{
var rig = new Rig();
rig.Availability.IsEnabled.Returns(false);
var sut = rig.Build();
var result = await sut.SendAsync(Message(), CancellationToken.None);
result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "disabled"));
(await sut.NotReadyReasonAsync(CancellationToken.None)).Should().Be("disabled");
await rig.Email.DidNotReceive().SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>());
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("not-an-address")]
public async Task WithoutAValidRecipient_NothingIsSent(string? recipient)
{
var rig = new Rig();
rig.Contact.RecipientEmail = recipient;
var sut = rig.Build();
var result = await sut.SendAsync(Message(), CancellationToken.None);
result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "recipient_not_configured"));
await rig.Email.DidNotReceive().SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>());
}
}
public class ContactMailServiceTests : IDisposable
{
private static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero);
private readonly string _dbName = Guid.NewGuid().ToString();
private readonly FakeTimeProvider _time = new(Now);
private readonly ContactOptions _options = new() { Enabled = true, SiteId = "site-a" };
private readonly IContactMailSender _sender = Substitute.For<IContactMailSender>();
private readonly CapturingLoggerProvider _logs = new();
private readonly ServiceProvider _provider;
public ContactMailServiceTests()
{
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns((string?)null);
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
var services = new ServiceCollection();
services.AddDbContext<ContactDbContext>(o => o.UseInMemoryDatabase(_dbName));
services.AddScoped<IContactRepository, ContactRepository>();
services.AddScoped(_ => _sender);
_provider = services.BuildServiceProvider();
}
public void Dispose() => _provider.Dispose();
private ContactMailService Sut() => new(
_provider.GetRequiredService<IServiceScopeFactory>(), new ContactMailSignal(), Options.Create(_options), _time,
LoggerFactory.Create(b => b.AddProvider(_logs)).CreateLogger<ContactMailService>());
private Guid Add(
ContactMessageStatus status = ContactMessageStatus.New, ContactMailStatus mail = ContactMailStatus.Pending,
int attempts = 0, DateTimeOffset? next = null, int minutesAgo = 0)
{
using var scope = _provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ContactDbContext>();
var message = new ContactMessage
{
Id = Guid.NewGuid(), SiteId = "site-a", ReceivedAt = Now.AddMinutes(-minutesAgo), Name = "Jan", Email = "jan@example.nl",
Subject = "s", Message = "m", Status = status, MailStatus = mail, MailAttempts = attempts,
NextMailAttemptAt = next ?? Now, RetentionUntil = Now.AddMonths(12),
};
db.ContactMessages.Add(message);
db.SaveChanges();
return message.Id;
}
private ContactMessage Get(Guid id)
{
using var scope = _provider.CreateScope();
return scope.ServiceProvider.GetRequiredService<ContactDbContext>().ContactMessages.AsNoTracking().Single(m => m.Id == id);
}
[Fact]
public async Task ADueMessage_IsSent_AndRecorded()
{
var id = Add();
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(1);
var m = Get(id);
m.MailStatus.Should().Be(ContactMailStatus.Sent);
m.MailAttempts.Should().Be(1);
m.NextMailAttemptAt.Should().BeNull();
m.MailError.Should().BeNull();
}
[Fact]
public async Task SpamReadArchivedAndAlreadySentMessages_AreNeverAutoMailed()
{
Add(ContactMessageStatus.Spam, ContactMailStatus.NotApplicable);
Add(ContactMessageStatus.Read);
Add(ContactMessageStatus.Archived);
Add(mail: ContactMailStatus.Sent);
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(0);
await _sender.DidNotReceive().SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task AFailure_IsRetriedWithTheBackoffSchedule_UntilTheMaximum_ThenNoMore()
{
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
.Returns(new ContactMailResult(ContactMailOutcome.Failed, "rejected"));
var id = Add();
var sut = Sut();
var expected = new[] { 5, 15, 60, 360, 1440 };
for (var attempt = 1; attempt <= 5; attempt++)
{
(await sut.SweepAsync(CancellationToken.None)).Should().Be(1);
var m = Get(id);
m.MailAttempts.Should().Be(attempt);
m.MailStatus.Should().Be(ContactMailStatus.Failed);
m.MailError.Should().Be("rejected");
m.NextMailAttemptAt.Should().Be(_time.GetUtcNow() + TimeSpan.FromMinutes(expected[attempt - 1]));
// Before the backoff has passed nothing is attempted.
(await sut.SweepAsync(CancellationToken.None)).Should().Be(0);
_time.Advance(TimeSpan.FromMinutes(expected[attempt - 1]));
}
(await sut.SweepAsync(CancellationToken.None)).Should().Be(1); // sixth and last
var last = Get(id);
last.MailAttempts.Should().Be(6);
last.NextMailAttemptAt.Should().BeNull();
_time.Advance(TimeSpan.FromDays(30));
(await sut.SweepAsync(CancellationToken.None)).Should().Be(0);
}
[Fact]
public async Task ARecoveryAfterAFailure_EndsAsSent()
{
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
.Returns(new ContactMailResult(ContactMailOutcome.Failed, "timeout"), new ContactMailResult(ContactMailOutcome.Sent));
var id = Add();
var sut = Sut();
await sut.SweepAsync(CancellationToken.None);
_time.Advance(TimeSpan.FromMinutes(5));
await sut.SweepAsync(CancellationToken.None);
var m = Get(id);
m.MailStatus.Should().Be(ContactMailStatus.Sent);
m.MailAttempts.Should().Be(2);
m.MailError.Should().BeNull();
}
[Fact]
public async Task WhenMailCannotBeSent_NothingIsAttemptedOrCounted_AndTheReasonIsShown()
{
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns("disabled");
var id = Add();
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(0);
var m = Get(id);
m.MailAttempts.Should().Be(0);
m.MailStatus.Should().Be(ContactMailStatus.Pending);
m.MailError.Should().Be("disabled");
await _sender.DidNotReceive().SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
// Once mail works again the same message goes out without any lost attempts.
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns((string?)null);
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(1);
Get(id).MailAttempts.Should().Be(1);
}
[Fact]
public async Task ASkippedSend_CountsNothing()
{
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
.Returns(new ContactMailResult(ContactMailOutcome.Skipped, "disabled"));
var id = Add();
await Sut().SweepAsync(CancellationToken.None);
var m = Get(id);
m.MailAttempts.Should().Be(0);
m.MailStatus.Should().Be(ContactMailStatus.Pending);
}
[Fact]
public async Task WhenTheModuleIsDisabled_NothingIsDone()
{
_options.Enabled = false;
Add();
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(0);
await _sender.DidNotReceive().SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task TheOldestMessagesGoFirst_AndTheBatchIsLimited()
{
_options.Mail.BatchSize = 2;
var oldest = Add(minutesAgo: 30);
var middle = Add(minutesAgo: 20);
var newest = Add(minutesAgo: 10);
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(2);
Get(oldest).MailStatus.Should().Be(ContactMailStatus.Sent);
Get(middle).MailStatus.Should().Be(ContactMailStatus.Sent);
Get(newest).MailStatus.Should().Be(ContactMailStatus.Pending);
}
[Fact]
public async Task AMessageClaimedByAnotherInstance_IsSkipped()
{
var id = Add();
// The other instance claims the message between our read and our claim.
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
using var scope = _provider.CreateScope();
var real = scope.ServiceProvider.GetRequiredService<IContactRepository>();
var due = await real.GetDueForMailAsync("site-a", Now, 6, 20, CancellationToken.None);
due.Should().HaveCount(1);
using (var other = _provider.CreateScope())
{
var db = other.ServiceProvider.GetRequiredService<ContactDbContext>();
var row = db.ContactMessages.Single(m => m.Id == id);
row.NextMailAttemptAt = Now.AddMinutes(5);
db.SaveChanges();
}
due[0].NextMailAttemptAt = Now.AddMinutes(5);
var act = async () => await real.SaveChangesAsync(CancellationToken.None);
await act.Should().ThrowAsync<DbUpdateConcurrencyException>();
}
[Fact]
public async Task TheLogs_CarryNoPersonalData()
{
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
.ThrowsAsync(new InvalidOperationException("cannot deliver to jan@example.nl"));
Add();
await Sut().SweepAsync(CancellationToken.None);
_logs.Messages.Should().NotContain(m => m.Contains("jan@example.nl"));
_logs.Messages.Should().Contain(m => m.Contains(nameof(InvalidOperationException)));
}
[Fact]
public async Task TheSignal_WakesTheWait_AndTheTimeoutAlsoReturns()
{
var signal = new ContactMailSignal();
signal.Notify();
await signal.WaitAsync(TimeSpan.FromSeconds(30), CancellationToken.None);
await signal.WaitAsync(TimeSpan.FromMilliseconds(50), CancellationToken.None);
}
}