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(); public IMailAvailability Availability { get; } = Substitute.For(); 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() .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); /// The real settings service on an in-memory database: the administrator's setting and the environment. public IContactSettingsService ContactSettings => new ContactSettingsService( new ContactRepository(_db), new ContactSettingsCache(TimeProvider.System), Options.Create(Contact), TimeProvider.System, Substitute.For()); public Rig() { Availability.IsEnabled.Returns(true); Email.SendAsync(Arg.Any(), Arg.Any()).Returns(call => { Sent = call.Arg(); return MailSendResult.Ok; }); } public ContactMailSender Build(string language = "nl") { var languages = Substitute.For(); languages.Resolve(Arg.Any()).Returns(language); var settings = Substitute.For(); settings.GetEffectiveSenderAsync(Arg.Any()).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()); } } 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: "\nregel2"), CancellationToken.None); rig.Sent!.HtmlBody.Should().NotContain("