This commit is contained in:
Zeeshaun
2026-03-31 16:43:12 -05:00
parent 9be174da46
commit d639027028
198 changed files with 111474 additions and 0 deletions
@@ -0,0 +1,130 @@
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using LCU.Library.Internal.MemberPreferencesApiModels.Entities;
using LCU.Library.Internal.MemberPreferencesApiModels.Enums;
using LCU.API.Internal.MemberPreferencesApi.Services.QueueServices;
using LCU.API.Internal.MemberPreferencesApi.Interfaces;
using LCU.API.Internal.MemberPreferencesApi.Configuration;
using LCU.API.Internal.MemberPreferencesApiLib.Repositories;
using LCU.API.Internal.MemberPreferencesApi.Services.DnaAuditServices;
using LCU.API.Internal.MemberPreferencesApi.MicroApiServices;
namespace LCU.API.Internal.MemberPreferencesApi.UnitTests.Services
{
public class DNADataAuditProcessServiceTest
{
private Mock<ICoreApiWrapperService> _coreApiWrapperServiceMock;
private Mock<IQueueDnaAccountAuditService> _queueAccountMock;
private Mock<IQueueDnaAgreementAuditService> _queueAgreementMock;
private Mock<IQueueDnaOrganizationAuditService> _queueOrganizationMock;
private Mock<IDnaAuditProcessRepository> _dnaAuditProcessRepositoryMock;
private DNADataAuditProcessService _service;
private Mock<IDateTime> _dateTimeMock;
private DnaAuditProcessConfiguration _config;
[SetUp]
public void Setup()
{
_dateTimeMock = new Mock<IDateTime>();
_config = new DnaAuditProcessConfiguration();
_coreApiWrapperServiceMock = new Mock<ICoreApiWrapperService>();
_queueAccountMock = new Mock<IQueueDnaAccountAuditService>();
_queueAgreementMock = new Mock<IQueueDnaAgreementAuditService>();
_queueOrganizationMock = new Mock<IQueueDnaOrganizationAuditService>();
_dnaAuditProcessRepositoryMock = new Mock<IDnaAuditProcessRepository>();
_service = new DNADataAuditProcessService(_queueAccountMock.Object, _queueAgreementMock.Object, _queueOrganizationMock.Object,
_coreApiWrapperServiceMock.Object, _dateTimeMock.Object, _dnaAuditProcessRepositoryMock.Object, _config);
}
[Test]
public async Task RunDnaAuditProcessesChange_HandleProcessUpdate_Ok()
{
var processlistAccount = new List<DnaAuditProcess>
{
new DnaAuditProcess()
{
ConsecutiveFailures = 0,
DnaProcessType = DnaAuditProcessType.DNAAccounts,
LastUpdated = DateTime.Now,
ProcessId = 0,
}
};
var processlistAgreement = new List<DnaAuditProcess>
{
new DnaAuditProcess()
{
ConsecutiveFailures = 0,
DnaProcessType = DnaAuditProcessType.DNAAgreement,
LastUpdated = DateTime.Now,
ProcessId = 0,
}
};
var processlistOrg = new List<DnaAuditProcess>
{
new DnaAuditProcess()
{
ConsecutiveFailures = 0,
DnaProcessType = DnaAuditProcessType.DNAOrganization,
LastUpdated = DateTime.Now,
ProcessId = 0,
}
};
await _service.RunDataAuditProcesses();
await _service.AuditDNAAccountsForTimePeriod(DateTime.Now, processlistAccount.First());
var resultAccount = _service.HandleDnaAuditProcessSuccess(processlistAccount.First());
await _service.AuditDNAAgreementForTimePeriod(DateTime.Now, processlistAgreement.First());
var resultAgreement = _service.HandleDnaAuditProcessSuccess(processlistAgreement.First());
await _service.AuditDNAOrganizationForTimePeriod(DateTime.Now, processlistOrg.First());
var resultOrg = _service.HandleDnaAuditProcessSuccess(processlistOrg.First());
//assert
Assert.NotNull(resultAccount);
Assert.AreEqual(resultAccount.DnaProcessType, DnaAuditProcessType.DNAAccounts);
Assert.AreEqual(resultAccount.ConsecutiveFailures, 0);
Assert.NotNull(resultAgreement);
Assert.AreEqual(resultAgreement.DnaProcessType, DnaAuditProcessType.DNAAgreement);
Assert.AreEqual(resultAgreement.ConsecutiveFailures, 0);
Assert.NotNull(resultOrg);
Assert.AreEqual(resultOrg.DnaProcessType, DnaAuditProcessType.DNAOrganization);
Assert.AreEqual(resultOrg.ConsecutiveFailures, 0);
}
[Test]
public async Task RunDnaAuditProcessesChange_HandleProcessUpdateException_Ok()
{
var processlistAccount = new List<DnaAuditProcess>
{
new DnaAuditProcess()
{
ConsecutiveFailures = 0,
DnaProcessType = DnaAuditProcessType.DNAAccounts,
LastUpdated = DateTime.Now,
ProcessId = 0,
}
};
var ex = new Exception();
await _service.RunDataAuditProcesses();
await _service.AuditDNAAccountsForTimePeriod(DateTime.Now, processlistAccount.First());
var resultAccount = _service.HandleDnaAuditProcessException(processlistAccount.First(), ex);
//assert
Assert.NotNull(resultAccount);
Assert.AreEqual(resultAccount.DnaProcessType, DnaAuditProcessType.DNAAccounts);
Assert.AreEqual(resultAccount.ConsecutiveFailures, 1);
}
}
}
@@ -0,0 +1,223 @@
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.API.Internal.MemberPreferencesApi.Services;
using LCU.Library.Internal.MemberPreferencesApiModels.Entities;
using LCU.Library.Internal.MemberPreferencesApiModels.Enums;
using LCU.Library.Internal.CoreApiWrapperModel.CoreModels.Agreements;
using LCU.API.Internal.MemberPreferencesApi.Services.DnaAuditServices;
using LCU.API.Internal.MemberPreferencesApi.MicroApiServices;
using LCU.API.Internal.MemberPreferencesApi.Models.Requests;
namespace LCU.API.Internal.MemberPreferencesApi.UnitTests.Services
{
public class DNADataAuditServiceTest
{
private Mock<ICoreApiWrapperService> _coreApiWrapperServiceMock;
private Mock<IOptinService> _optinServiceMock;
private DNADataAuditService _service;
[SetUp]
public void Setup()
{
_coreApiWrapperServiceMock = new Mock<ICoreApiWrapperService>();
_optinServiceMock = new Mock<IOptinService>();
_service = new DNADataAuditService(_coreApiWrapperServiceMock.Object, _optinServiceMock.Object);
}
[Test]
public async Task HandleChangedFields_AccountChange_OK_UPDATE()
{
var account = new AgreementAccount
{
AccountNumber = 123456,
OvrDeliveryMethCD = "PRNT",
AccountOwner = new AgreementAccountOwner
{
AccountNumber = 123456,
AgreementNumber = 222,
PersonNumber = 123,
UserId = "1234"
}
};
var memberOptinSettings = new MemberOptInSettings
{
EStatements = null,
UniversalOptIn = "Electronic"
};
//setup
_coreApiWrapperServiceMock.Setup(x => x.GetAgreementAccountByAccountId(123456)).ReturnsAsync(account).Verifiable();
_optinServiceMock.Setup(x => x.GetMemberOptInSettings("1234")).ReturnsAsync(memberOptinSettings).Verifiable();
var request = new DnaFieldChangeRequest()
{
ConsecutiveFailures = 0,
DnaFieldIdInformation = 123456L,
DnaProcessType = DnaAuditProcessType.DNAAgreement,
LastUpdated = DateTime.Now,
ProcessId = 1
};
await _service.HandleAccountAuditCheck(request);
//assert
_coreApiWrapperServiceMock.Verify(x => x.UpdateAgreementAccountsDeliveryMethod(It.Is<List<long>>(list => list.Contains(123456)), It.Is<string>(x => x.Equals("WWW")), It.Is<string>(x => x.Equals("1234"))), Times.Once);
_coreApiWrapperServiceMock.Verify();
_optinServiceMock.Verify();
}
[Test]
public async Task HandleChangedFields_AccountChange_OK_DONTUPDATE()
{
var account = new AgreementAccount
{
AccountNumber = 123456,
OvrDeliveryMethCD = "PRNT",
AccountOwner = new AgreementAccountOwner
{
AccountNumber = 123456,
AgreementNumber = 222,
PersonNumber = 123,
UserId = "1234"
}
};
var memberOptinSettings = new MemberOptInSettings
{
EStatements = null,
UniversalOptIn = "Paper"
};
//setup
_coreApiWrapperServiceMock.Setup(x => x.GetAgreementAccountByAccountId(123456)).ReturnsAsync(account).Verifiable();
_optinServiceMock.Setup(x => x.GetMemberOptInSettings("1234"))
.ReturnsAsync(memberOptinSettings).Verifiable();
var request = new DnaFieldChangeRequest()
{
ConsecutiveFailures = 0,
DnaFieldIdInformation = 123456L,
DnaProcessType = DnaAuditProcessType.DNAAccounts,
LastUpdated = DateTime.Now,
ProcessId = 1
};
await _service.HandleAccountAuditCheck(request);
//assert
_coreApiWrapperServiceMock.Verify(x => x.UpdateAgreementAccountsDeliveryMethod(It.IsAny<List<long>>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_coreApiWrapperServiceMock.Verify();
_optinServiceMock.Verify();
}
[Test]
public async Task HandleChangedFields_AgreementChange_OK_UPDATE()
{
var agreement = new Agreement
{
AgreementNumber = 1127,
PersonNumber = 123,
UserId = "1234"
};
var accounts = new List<AgreementAccount>
{
new AgreementAccount{
AccountNumber = 123456,
OvrDeliveryMethCD = "PRNT",
TaxReportForPersonNumber = 123,
AccountOwner = new AgreementAccountOwner{
AccountNumber = 123456,
AgreementNumber = 1127,
PersonNumber = 123,
UserId = "1234"
}
}
};
var memberOptinSettings = new MemberOptInSettings
{
EStatements = null,
UniversalOptIn = "Electronic"
};
//setup
_coreApiWrapperServiceMock.Setup(x => x.GetAgreementByAgreementId(1127)).ReturnsAsync(agreement).Verifiable();
_coreApiWrapperServiceMock.Setup(x => x.GetAgreementAccountsByUserId("1234")).ReturnsAsync(accounts).Verifiable();
_optinServiceMock.Setup(x => x.GetMemberOptInSettings("1234")).ReturnsAsync(memberOptinSettings).Verifiable();
var request = new DnaFieldChangeRequest()
{
ConsecutiveFailures = 0,
DnaFieldIdInformation = 1127L,
DnaProcessType = DnaAuditProcessType.DNAAgreement,
LastUpdated = DateTime.Now,
ProcessId = 1
};
await _service.HandleAgreementAuditCheck(request);
//assert
_coreApiWrapperServiceMock.Verify(x => x.UpdateAgreementAccountsDeliveryMethod(It.Is<List<long>>(list => list.Contains(123456)), It.Is<string>(x => x.Equals("WWW")), It.Is<string>(x => x.Equals("1234"))), Times.Once);
_coreApiWrapperServiceMock.Verify();
_optinServiceMock.Verify();
}
[Test]
public async Task HandleChangedFields_OrganizationChange_OK_UPDATE()
{
var accounts = new List<AgreementAccount>
{
new AgreementAccount{
AccountNumber = 123456,
TaxReportForOrgNumber = 11267,
OvrDeliveryMethCD = "PRNT",
AccountOwner = new AgreementAccountOwner
{
AccountNumber = 123456,
AgreementNumber = 222,
PersonNumber = 123,
UserId = "1234"
}
}
};
var memberOptinSettings = new MemberOptInSettings
{
EStatements = null,
UniversalOptIn = "Electronic"
};
//setup
_coreApiWrapperServiceMock.Setup(x => x.GetAgreementAccountsByOrganizationId(1126)).ReturnsAsync(accounts).Verifiable();
_optinServiceMock.Setup(x => x.GetMemberOptInSettings("1234")).ReturnsAsync(memberOptinSettings).Verifiable();
var request = new DnaFieldChangeRequest()
{
ConsecutiveFailures = 0,
DnaFieldIdInformation = 1126L,
DnaProcessType = DnaAuditProcessType.DNAAgreement,
LastUpdated = DateTime.Now,
ProcessId = 1
};
//act
await _service.HandleOrganizationAuditCheck(request);
//assert
_coreApiWrapperServiceMock.Verify(x => x.UpdateAgreementAccountsDeliveryMethod(It.Is<List<long>>(list => list.Contains(123456)), It.Is<string>(x => x.Equals("WWW")), It.Is<string>(x => x.Equals("1234"))), Times.Once);
_coreApiWrapperServiceMock.Verify();
_optinServiceMock.Verify();
}
}
}
@@ -0,0 +1,882 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.API.Internal.MemberPreferencesApi.Services;
using LCU.API.Internal.MemberPreferencesApiLib.Repositories;
using LCU.API.Internal.MemberPreferencesApi.Models.EmailPolicies;
using LCU.Library.Internal.MemberPreferencesApiModels.Entities;
using LCU.Library.Internal.MemberPreferencesApiModels.Enums;
using Moq;
using Newtonsoft.Json;
using NUnit.Framework;
namespace LCU.API.Internal.MemberPreferencesApi.UnitTests.Services
{
public class MemberEmailServiceTest
{
private readonly IMemberEmailService _service;
private readonly FakeUnifiedOptInRepository _repository;
private readonly Mock<IIntegrationService> _mockIntegrationService;
private readonly Mock<IMemberPreferenceService> _mockPreferenceService;
private readonly Mock<IEmailFailurePolicy>[] _policies =
{
new Mock<IEmailFailurePolicy>(),
new Mock<IEmailFailurePolicy>()
};
public MemberEmailServiceTest()
{
var unitOfWork = new FakeUnitOfWork();
_repository = new FakeUnifiedOptInRepository(unitOfWork);
_mockIntegrationService = new Mock<IIntegrationService>();
_mockPreferenceService = new Mock<IMemberPreferenceService>();
_service = new MemberEmailService(_repository, unitOfWork, _policies.Select(p => p.Object), _mockPreferenceService.Object, _mockIntegrationService.Object);
}
private static readonly (DateTime? firstSent, DateTime? lastSent, EmailStatus PriorStatus, int count)[]
PreUpdateStateScenarios =
{
(null, null, EmailStatus.FailingDelivery, 1),
(DateTime.Now.AddHours(-2), null, EmailStatus.FailingDelivery, 2),
(null, DateTime.Now.AddHours(-3), EmailStatus.FailingDelivery, 3),
(DateTime.Now.AddHours(-4), DateTime.Now.AddHours(-4), EmailStatus.FailingDelivery, 4),
(null, null, EmailStatus.DeliveredSuccessfully, 5),
(DateTime.Now.AddHours(-6), null, EmailStatus.DeliveredSuccessfully, 6),
(null, DateTime.Now.AddHours(-7), EmailStatus.DeliveredSuccessfully, 7),
(DateTime.Now.AddHours(-8), DateTime.Now.AddHours(-8), EmailStatus.DeliveredSuccessfully, 8),
};
private static readonly (bool isUnifiedOptIn, bool matchesUnifiedOptin, bool matchesENotification, bool matchesEstatement)[]
MatchScenarios =
{
(true, true, true, true),
(true, true, true, false),
(true, true, false, true),
(true, true, false, false),
(false, false, true, true),
(false, false, true, false),
(false, false, false, true),
(false, false, true, true),
(false, false, true, false),
(false, false, false, true),
};
private static IEnumerable<object> CombinedScenarios()
{
foreach (var match in MatchScenarios)
{
foreach (var state in PreUpdateStateScenarios)
{
yield return new UpdateScenario(state, match);
}
}
}
private static readonly object[] UpdateScenarios = CombinedScenarios().ToArray();
private static readonly Random Random = new Random(DateTime.Now.Millisecond);
private static string EmailAddressFactory()
{
static char RandomLetter() => (char)('a' + Random.Next(0, 26));
return string.Concat
(
Enumerable.Repeat<Func<char>>(RandomLetter, Random.Next(5, 50)).Select(f => f())
)
.RandomizeCase();
}
[Test]
public async Task EmailSucceededToSend_UserOptInSettingsNotFound_ReturnsFalse()
{
var userId = Guid.NewGuid().ToString();
_repository.MemberOptInSettings.Remove(userId);
var updated = await _service.EmailSucceededToSend(userId, Guid.NewGuid().ToString());
Assert.IsFalse(updated);
}
[Test]
public async Task EmailSucceededToSend_NoEmailMatches_ReturnsFalse()
{
var userId = Guid.NewGuid().ToString();
var email = EmailAddressFactory();
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = EmailAddressFactory(),
EStatementsEmail = EmailAddressFactory(),
ENotificationsEmail = EmailAddressFactory()
};
var updated = await _service.EmailSucceededToSend(userId, email);
Assert.IsFalse(updated);
}
[Test]
public async Task EmailSucceededToSend_NullEmailNoMatches_ReturnsFalse()
{
var userId = Guid.NewGuid().ToString();
string email = null;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = EmailAddressFactory(),
EStatementsEmail = EmailAddressFactory(),
ENotificationsEmail = EmailAddressFactory()
};
var updated = await _service.EmailSucceededToSend(userId, email);
Assert.IsFalse(updated);
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailSucceededToSend_EmailMatchesRegardlessOfCase_ReturnsTrue(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
var email = EmailAddressFactory();
var unmatchedEmail = EmailAddressFactory();
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = scenario.MatchScenario.matchesUnifiedOptin ? email.RandomizeCase() : unmatchedEmail,
EStatementsEmail = scenario.MatchScenario.matchesEstatement ? email.RandomizeCase() : unmatchedEmail,
ENotificationsEmail = scenario.MatchScenario.matchesENotification ? email.RandomizeCase() : unmatchedEmail
};
var updated = await _service.EmailSucceededToSend(userId, email);
Assert.IsTrue(updated);
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailSucceededToSend_NullEmailMatched_ReturnsTrue(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
string email = null;
var unmatchedEmail = EmailAddressFactory();
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = scenario.MatchScenario.matchesUnifiedOptin ? null : unmatchedEmail,
EStatementsEmail = scenario.MatchScenario.matchesEstatement ? null : unmatchedEmail,
ENotificationsEmail = scenario.MatchScenario.matchesENotification ? null : unmatchedEmail
};
var updated = await _service.EmailSucceededToSend(userId, email);
Assert.IsTrue(updated);
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailSucceededToSend_EmailMatchesRegardlessOfCase_UpdatesTrackingOnMatched(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
var email = EmailAddressFactory();
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = matchesUnifiedOptin ? email.RandomizeCase() : unmatchedEmail,
UnifiedOptInEmailFirstSent = firstSent,
UnifiedOptInEmailLastSent = lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement ? email.RandomizeCase() : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification ? email.RandomizeCase() : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
var actionStart = DateTime.Now;
await _service.EmailSucceededToSend(userId, email);
var elapsedActionTime = DateTime.Now - actionStart;
var updatedSettings = _repository.MemberOptInSettings[userId];
if (matchesUnifiedOptin)
{
Assert.IsNull(updatedSettings.UnifiedOptInEmailFirstSent);
Assert.That(updatedSettings.UnifiedOptInEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.DeliveredSuccessfully, updatedSettings.UnifiedOptInEmailStatus);
Assert.AreEqual(0, updatedSettings.UnifiedOptInEmailStatusCount);
}
if (matchesEstatement)
{
Assert.IsNull(updatedSettings.EStatementsEmailFirstSent);
Assert.That(updatedSettings.EStatementsEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.DeliveredSuccessfully, updatedSettings.EStatementsEmailStatus);
Assert.AreEqual(0, updatedSettings.EStatementsEmailStatusCount);
}
if (matchesENotification)
{
Assert.IsNull(updatedSettings.ENotificationsEmailFirstSent);
Assert.That(updatedSettings.ENotificationsEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.DeliveredSuccessfully, updatedSettings.ENotificationsEmailStatus);
Assert.AreEqual(0, updatedSettings.ENotificationsEmailStatusCount);
}
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailSucceededToSend_NullEmailMatched_UpdatesTrackingOnMatched(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
string email = null;
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = matchesUnifiedOptin ? null : unmatchedEmail,
UnifiedOptInEmailFirstSent = firstSent,
UnifiedOptInEmailLastSent = lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement ? null : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification ? null : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
var actionStart = DateTime.Now;
await _service.EmailSucceededToSend(userId, email);
var elapsedActionTime = DateTime.Now - actionStart;
var updatedSettings = _repository.MemberOptInSettings[userId];
if (matchesUnifiedOptin)
{
Assert.IsNull(updatedSettings.UnifiedOptInEmailFirstSent);
Assert.That(updatedSettings.UnifiedOptInEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.DeliveredSuccessfully, updatedSettings.UnifiedOptInEmailStatus);
Assert.AreEqual(0, updatedSettings.UnifiedOptInEmailStatusCount);
}
if (matchesEstatement)
{
Assert.IsNull(updatedSettings.EStatementsEmailFirstSent);
Assert.That(updatedSettings.EStatementsEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.DeliveredSuccessfully, updatedSettings.EStatementsEmailStatus);
Assert.AreEqual(0, updatedSettings.EStatementsEmailStatusCount);
}
if (matchesENotification)
{
Assert.IsNull(updatedSettings.ENotificationsEmailFirstSent);
Assert.That(updatedSettings.ENotificationsEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.DeliveredSuccessfully, updatedSettings.ENotificationsEmailStatus);
Assert.AreEqual(0, updatedSettings.ENotificationsEmailStatusCount);
}
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailSucceededToSend_EmailMatchesRegardlessOfCase_DoesNotUpdateTrackingOnUnmatched(
UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
var email = EmailAddressFactory();
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = matchesUnifiedOptin ? email.RandomizeCase() : unmatchedEmail,
UnifiedOptInEmailFirstSent = firstSent,
UnifiedOptInEmailLastSent = lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement ? email.RandomizeCase() : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification ? email.RandomizeCase() : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
await _service.EmailSucceededToSend(userId, email);
var updatedSettings = _repository.MemberOptInSettings[userId];
if (!matchesUnifiedOptin)
{
Assert.AreEqual(firstSent, updatedSettings.UnifiedOptInEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.UnifiedOptInEmailLastSent);
Assert.AreEqual(status, updatedSettings.UnifiedOptInEmailStatus);
Assert.AreEqual(count, updatedSettings.UnifiedOptInEmailStatusCount);
}
if (!matchesEstatement)
{
Assert.AreEqual(firstSent, updatedSettings.EStatementsEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.EStatementsEmailLastSent);
Assert.AreEqual(status, updatedSettings.EStatementsEmailStatus);
Assert.AreEqual(count, updatedSettings.EStatementsEmailStatusCount);
}
if (!matchesENotification)
{
Assert.AreEqual(firstSent, updatedSettings.ENotificationsEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.ENotificationsEmailLastSent);
Assert.AreEqual(status, updatedSettings.ENotificationsEmailStatus);
Assert.AreEqual(count, updatedSettings.ENotificationsEmailStatusCount);
}
}
[Test]
public async Task EmailFailedToSend_UserOptInSettingsNotFound_ReturnsFalse()
{
var userId = Guid.NewGuid().ToString();
_repository.MemberOptInSettings.Remove(userId);
var updated = await _service.EmailFailedToSend(userId, EmailAddressFactory(), true);
Assert.IsFalse(updated);
}
[Test]
public async Task EmailFailedToSend_EmailMatchesNoOptinEmailPreference_ReturnsFalse()
{
var userId = Guid.NewGuid().ToString();
var email = EmailAddressFactory();
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = EmailAddressFactory(),
EStatementsEmail = EmailAddressFactory(),
ENotificationsEmail = EmailAddressFactory()
};
var updated = await _service.EmailFailedToSend(userId, email, true);
Assert.IsFalse(updated);
}
[Test]
public async Task EmailFailedToSend_NullEmailMatchesNoOptinEmailPreference_ReturnsFalse()
{
var userId = Guid.NewGuid().ToString();
string email = null;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = EmailAddressFactory(),
EStatementsEmail = EmailAddressFactory(),
ENotificationsEmail = EmailAddressFactory()
};
var updated = await _service.EmailFailedToSend(userId, email, true);
Assert.IsFalse(updated);
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailFailedToSend_EmailMatchesRegardlessOfCase_ReturnsTrue(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
var email = EmailAddressFactory();
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UniversalOptIn = isUniversalOptin ? "Electronic" : null,
UnifiedOptInEmail = matchesUnifiedOptin && isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
UnifiedOptInEmailFirstSent = isUniversalOptin ? DateTime.Now : firstSent,
UnifiedOptInEmailLastSent = isUniversalOptin ? DateTime.Now : lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement && !isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification && !isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
var updated = await _service.EmailFailedToSend(userId, email, true);
Assert.IsTrue(updated);
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailFailedToSend_NullEmailMatched_ReturnsTrue(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
string email = null;
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UniversalOptIn = isUniversalOptin ? "Electronic" : null,
UnifiedOptInEmail = matchesUnifiedOptin && isUniversalOptin ? null : unmatchedEmail,
UnifiedOptInEmailFirstSent = firstSent,
UnifiedOptInEmailLastSent = lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement && !isUniversalOptin ? null : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification && !isUniversalOptin ? null : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
var updated = await _service.EmailFailedToSend(userId, email, true);
var updatedSettings = _repository.MemberOptInSettings[userId];
Assert.IsTrue(updated);
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailFailedToSend_EmailMatchesRegardlessOfCase_UpdatesTrackingOnMatched(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
var email = EmailAddressFactory();
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UniversalOptIn = isUniversalOptin ? "Electronic" : null,
UnifiedOptInEmail = matchesUnifiedOptin && isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
UnifiedOptInEmailFirstSent = firstSent,
UnifiedOptInEmailLastSent = lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement && !isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification && !isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
var actionStart = DateTime.Now;
await _service.EmailFailedToSend(userId, email, true);
var elapsedActionTime = DateTime.Now - actionStart;
var updatedSettings = _repository.MemberOptInSettings[userId];
var updatedFirstSent = firstSent is null
? Is.EqualTo(actionStart).Within(elapsedActionTime)
: Is.EqualTo(firstSent);
if (matchesUnifiedOptin && isUniversalOptin)
{
Assert.That(updatedSettings.UnifiedOptInEmailFirstSent, updatedFirstSent);
Assert.That(updatedSettings.UnifiedOptInEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.FailingDelivery, updatedSettings.UnifiedOptInEmailStatus);
Assert.AreEqual(count + 1, updatedSettings.UnifiedOptInEmailStatusCount);
}
if (matchesEstatement && !isUniversalOptin)
{
Assert.That(updatedSettings.EStatementsEmailFirstSent, updatedFirstSent);
Assert.That(updatedSettings.EStatementsEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.FailingDelivery, updatedSettings.EStatementsEmailStatus);
Assert.AreEqual(count + 1, updatedSettings.EStatementsEmailStatusCount);
}
if (matchesENotification && !isUniversalOptin)
{
Assert.That(updatedSettings.ENotificationsEmailFirstSent, updatedFirstSent);
Assert.That(updatedSettings.ENotificationsEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.FailingDelivery, updatedSettings.ENotificationsEmailStatus);
Assert.AreEqual(count + 1, updatedSettings.ENotificationsEmailStatusCount);
}
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailFailedToSend_NullEmailMatched_UpdatesTrackingOnMatched(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
string email = null;
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UniversalOptIn = isUniversalOptin ? "Electronic" : null,
UnifiedOptInEmail = matchesUnifiedOptin && isUniversalOptin ? null : unmatchedEmail,
UnifiedOptInEmailFirstSent = firstSent,
UnifiedOptInEmailLastSent = lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement && !isUniversalOptin ? null : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification && !isUniversalOptin ? null : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
var actionStart = DateTime.Now;
await _service.EmailFailedToSend(userId, email, true);
var elapsedActionTime = DateTime.Now - actionStart;
var updatedSettings = _repository.MemberOptInSettings[userId];
var updatedFirstSent = firstSent is null
? Is.EqualTo(actionStart).Within(elapsedActionTime)
: Is.EqualTo(firstSent);
if (matchesUnifiedOptin && isUniversalOptin)
{
Assert.That(updatedSettings.UnifiedOptInEmailFirstSent, updatedFirstSent);
Assert.That(updatedSettings.UnifiedOptInEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.FailingDelivery, updatedSettings.UnifiedOptInEmailStatus);
Assert.AreEqual(count + 1, updatedSettings.UnifiedOptInEmailStatusCount);
}
if (matchesEstatement && !isUniversalOptin)
{
Assert.That(updatedSettings.EStatementsEmailFirstSent, updatedFirstSent);
Assert.That(updatedSettings.EStatementsEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.FailingDelivery, updatedSettings.EStatementsEmailStatus);
Assert.AreEqual(count + 1, updatedSettings.EStatementsEmailStatusCount);
}
if (matchesENotification && !isUniversalOptin)
{
Assert.That(updatedSettings.ENotificationsEmailFirstSent, updatedFirstSent);
Assert.That(updatedSettings.ENotificationsEmailLastSent,
Is.EqualTo(actionStart).Within(elapsedActionTime));
Assert.AreEqual(EmailStatus.FailingDelivery, updatedSettings.ENotificationsEmailStatus);
Assert.AreEqual(count + 1, updatedSettings.ENotificationsEmailStatusCount);
}
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailFailedToSend_EmailMatchesRegardlessOfCase_DoesNotUpdateTrackingOnUnmatched(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
var email = EmailAddressFactory();
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = matchesUnifiedOptin && isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
UnifiedOptInEmailFirstSent = firstSent,
UnifiedOptInEmailLastSent = lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement && !isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification && !isUniversalOptin ? email.RandomizeCase() : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
await _service.EmailFailedToSend(userId, email, true);
var updatedSettings = _repository.MemberOptInSettings[userId];
if (!matchesUnifiedOptin)
{
Assert.AreEqual(firstSent, updatedSettings.UnifiedOptInEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.UnifiedOptInEmailLastSent);
Assert.AreEqual(status, updatedSettings.UnifiedOptInEmailStatus);
Assert.AreEqual(count, updatedSettings.UnifiedOptInEmailStatusCount);
}
if (!matchesEstatement)
{
Assert.AreEqual(firstSent, updatedSettings.EStatementsEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.EStatementsEmailLastSent);
Assert.AreEqual(status, updatedSettings.EStatementsEmailStatus);
Assert.AreEqual(count, updatedSettings.EStatementsEmailStatusCount);
}
if (!matchesENotification)
{
Assert.AreEqual(firstSent, updatedSettings.ENotificationsEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.ENotificationsEmailLastSent);
Assert.AreEqual(status, updatedSettings.ENotificationsEmailStatus);
Assert.AreEqual(count, updatedSettings.ENotificationsEmailStatusCount);
}
}
[TestCaseSource(nameof(UpdateScenarios))]
public async Task EmailFailedToSend_NullEmailMatched_DoesNotUpdateTrackingOnUnmatched(UpdateScenario scenario)
{
var userId = Guid.NewGuid().ToString();
string email = null;
var unmatchedEmail = EmailAddressFactory();
var (isUniversalOptin, matchesUnifiedOptin, matchesEstatement, matchesENotification) = scenario.MatchScenario;
var (firstSent, lastSent, status, count) = scenario.PriorState;
_repository.MemberOptInSettings[userId] = new MemberOptInSettings
{
UnifiedOptInEmail = matchesUnifiedOptin ? null : unmatchedEmail,
UnifiedOptInEmailFirstSent = firstSent,
UnifiedOptInEmailLastSent = lastSent,
UnifiedOptInEmailStatus = status,
UnifiedOptInEmailStatusCount = count,
EStatementsEmail = matchesEstatement ? null : unmatchedEmail,
EStatementsEmailFirstSent = firstSent,
EStatementsEmailLastSent = lastSent,
EStatementsEmailStatus = status,
EStatementsEmailStatusCount = count,
ENotificationsEmail = matchesENotification ? null : unmatchedEmail,
ENotificationsEmailFirstSent = firstSent,
ENotificationsEmailLastSent = lastSent,
ENotificationsEmailStatus = status,
ENotificationsEmailStatusCount = count
};
await _service.EmailFailedToSend(userId, email, true);
var updatedSettings = _repository.MemberOptInSettings[userId];
if (!matchesUnifiedOptin)
{
Assert.AreEqual(firstSent, updatedSettings.UnifiedOptInEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.UnifiedOptInEmailLastSent);
Assert.AreEqual(status, updatedSettings.UnifiedOptInEmailStatus);
Assert.AreEqual(count, updatedSettings.UnifiedOptInEmailStatusCount);
}
if (!matchesEstatement)
{
Assert.AreEqual(firstSent, updatedSettings.EStatementsEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.EStatementsEmailLastSent);
Assert.AreEqual(status, updatedSettings.EStatementsEmailStatus);
Assert.AreEqual(count, updatedSettings.EStatementsEmailStatusCount);
}
if (!matchesENotification)
{
Assert.AreEqual(firstSent, updatedSettings.ENotificationsEmailFirstSent);
Assert.AreEqual(lastSent, updatedSettings.ENotificationsEmailLastSent);
Assert.AreEqual(status, updatedSettings.ENotificationsEmailStatus);
Assert.AreEqual(count, updatedSettings.ENotificationsEmailStatusCount);
}
}
[Test]
public async Task EmailFailedToSend_PolicyMakesUpdate_ReturnsTrue()
{
var userId = Guid.NewGuid().ToString();
_repository.MemberOptInSettings[userId] = new MemberOptInSettings { UserId = userId, EStatementsEmail = "" };
_policies[1]
.Setup(p => p.Apply(It.Is<MemberOptInSettings>(s => s.UserId == userId), It.IsAny<bool>()))
.ReturnsAsync(true);
var updated = await _service.EmailFailedToSend(userId, string.Empty, true);
Assert.IsTrue(updated);
}
[Test]
public async Task EmailFailedToSend_PolicyMakesUpdate_FeatureFlagReturnsFalse()
{
var userId = Guid.NewGuid().ToString();
_repository.MemberOptInSettings[userId] = new MemberOptInSettings { UserId = userId };
_policies[1]
.Setup(p => p.Apply(It.Is<MemberOptInSettings>(s => s.UserId == userId), It.IsAny<bool>()))
.ReturnsAsync(false);
var updated = await _service.EmailFailedToSend(userId, string.Empty, false);
Assert.IsFalse(updated);
}
[Test]
public async Task EmailFailedToSend_PolicyMakesUpdate_UpdatesTracking()
{
var userId = Guid.NewGuid().ToString();
_repository.MemberOptInSettings[userId] = new MemberOptInSettings { UserId = userId };
_policies[1]
.Setup(p => p.Apply(It.Is<MemberOptInSettings>(s => s.UserId == userId), It.IsAny<bool>()))
.Callback<MemberOptInSettings, bool>((s, b) => s.LastUpdatedBy = nameof(EmailFailedToSend_PolicyMakesUpdate_UpdatesTracking))
.ReturnsAsync(true);
await _service.EmailFailedToSend(userId, string.Empty, true);
var updatedSettings = _repository.MemberOptInSettings[userId];
Assert.AreEqual(nameof(EmailFailedToSend_PolicyMakesUpdate_UpdatesTracking), updatedSettings.LastUpdatedBy);
}
[Test]
public async Task EmailFailedToSend_AllCases_EvaluatesAllFailurePolicies()
{
var userId = Guid.NewGuid().ToString();
_repository.MemberOptInSettings[userId] = new MemberOptInSettings { UserId = userId };
_policies[1]
.Setup(p => p.Apply(It.Is<MemberOptInSettings>(s => s.UserId == userId), It.IsAny<bool>()))
.ReturnsAsync(true);
await _service.EmailFailedToSend(userId, string.Empty, true);
foreach (var policy in _policies)
{
policy.Verify(p => p.Apply(It.Is<MemberOptInSettings>(s => s.UserId == userId), It.IsAny<bool>()));
}
}
private interface IObservableRepository<in TKey, in TValue>
{
void ApplyChanges(TKey key, TValue value);
}
private class FakeUnifiedOptInRepository : IUnifiedOptInRepository,
IObservableRepository<string, MemberOptInSettings>
{
public IDictionary<string, MemberOptInSettings> MemberOptInSettings { get; } =
new Dictionary<string, MemberOptInSettings>();
private readonly IRepositoryObserver<string, MemberOptInSettings> _observer;
public FakeUnifiedOptInRepository(IRepositoryObserver<string, MemberOptInSettings> observer)
{
_observer = observer;
_observer.Observe(this);
}
public Task<MemberOptInSettings> GetMemberOptInSettings(string userId)
{
if (!MemberOptInSettings.TryGetValue(userId, out var optInSettings))
{
return Task.FromResult<MemberOptInSettings>(null);
}
var clonedSettings = JsonConvert.DeserializeObject<MemberOptInSettings>
(
JsonConvert.SerializeObject(optInSettings)
);
_observer.Track(userId, clonedSettings);
return Task.FromResult(clonedSettings);
}
public Task<MemberOptInSettings> GetMemberOptInSettingsNoTracking(string userId)
{
throw new NotImplementedException();
}
public Task<MemberOptInSettings> GetOrCreateMemberOptinSettings(string userId)
{
throw new NotImplementedException();
}
public Task<List<MemberOptInSettings>> GetAllMemberOptInSettings(List<string> memberNumbers)
{
throw new NotImplementedException();
}
public void ApplyChanges(string key, MemberOptInSettings value)
{
MemberOptInSettings[key] = value;
}
}
private interface IRepositoryObserver<TKey, TValue>
{
void Track(TKey key, TValue value);
void Observe(IObservableRepository<TKey, TValue> subject);
}
private class FakeUnitOfWork : IUnitOfWork, IRepositoryObserver<string, MemberOptInSettings>
{
private readonly IDictionary<string, MemberOptInSettings> _activeRecords =
new Dictionary<string, MemberOptInSettings>();
private IObservableRepository<string, MemberOptInSettings> _subject;
public Task CompleteAsync()
{
foreach (var record in _activeRecords)
{
_subject.ApplyChanges(record.Key, record.Value);
}
return Task.CompletedTask;
}
public Task CompleteAsync(string operatorId, DateTime dateAdded, UserType userType)
{
return CompleteAsync();
}
public void Track(string key, MemberOptInSettings value)
{
_activeRecords[key] = value;
}
public void Observe(IObservableRepository<string, MemberOptInSettings> subject)
{
_subject = subject;
}
}
public struct UpdateScenario
{
public (DateTime? firstSent, DateTime? lastSent, EmailStatus status, int count) PriorState { get; }
public (bool isUniversalOptIn, bool matchesUnifiedOptin, bool matchesENotification, bool matchesEstatement) MatchScenario { get; }
public UpdateScenario((DateTime? firstSent, DateTime? lastSent, EmailStatus status, int count) priorState,
(bool isUniveralsOptin, bool matchesUnifiedOptin, bool matchesENotification, bool matchesEstatement) matchScenario)
{
PriorState = priorState;
MatchScenario = matchScenario;
}
}
}
}
public static class RandomCaseExtension
{
private static readonly Random Random = new Random(DateTime.Now.Millisecond);
public static string RandomizeCase(this string s)
{
static char RandomCase(char c) => Random.Next() % 2 == 0 ? char.ToUpper(c) : char.ToLower(c);
return string.Concat(s.Select(RandomCase));
}
}
@@ -0,0 +1,895 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using LCU.API.Internal.MemberPreferencesApi.DataAccess;
using LCU.API.Internal.MemberPreferencesApi.Services;
using LCU.Library.Internal.MemberPreferencesApiModels.Entities;
using LCU.Library.Internal.MemberPreferencesApiModels.Enums;
using Infrastructure.Services;
using LCU.Library.Internal.CoreApiWrapperModel.CoreModels.Agreements;
using Microsoft.EntityFrameworkCore;
using Moq;
using NUnit.Framework;
using LCU.Library.Internal.MemberPreferencesApiModels.Requests;
using LCU.API.Internal.MemberPreferencesApiLib.Repositories;
using LCU.API.Internal.MemberPreferencesApiLib.Persistence;
using LCU.API.Internal.MemberPreferencesApi.Services.XdiServices;
using LCU.API.Internal.MemberPreferencesApi.MicroApiServices;
namespace LCU.API.Internal.MemberPreferencesApi.UnitTests.Services
{
public class MemberPreferenceServiceTest
{
private MemberPreferenceService _memberPreferenceService;
private IMemberPreferenceRepository _memberPreferenceRepository;
private IUnifiedOptInRepository _unifiedOptInRepository;
private Mock<INotificationService> _mockNotificationService;
private Mock<IIntegrationService> _mockIntegrationService;
private Mock<IXdiBatchService> _xdiBatchItemServiceMock;
private Mock<ICoreApiWrapperService> _mockCoreApiWrapperService;
[SetUp]
public void Setup()
{
var mockDateTime = new DateTimeService();
_mockNotificationService = new Mock<INotificationService>();
_mockIntegrationService = new Mock<IIntegrationService>();
_xdiBatchItemServiceMock = new Mock<IXdiBatchService>();
_mockCoreApiWrapperService = new Mock<ICoreApiWrapperService>();
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.EnableSensitiveDataLogging()
.Options;
var context = new ApplicationDbContext(options);
_memberPreferenceRepository = new MemberPreferenceRepository(context);
_unifiedOptInRepository = new UnifiedOptInRepository(context);
_memberPreferenceService = new MemberPreferenceService(_memberPreferenceRepository, new UnitOfWork(context),
_unifiedOptInRepository, _mockNotificationService.Object, _mockIntegrationService.Object,
_xdiBatchItemServiceMock.Object, _mockCoreApiWrapperService.Object);
}
[Test]
public async Task Basic_Flow()
{
var saved = await _memberPreferenceService.GetMemberPreferencesAsync("99");
Assert.NotNull(saved);
Assert.IsEmpty(saved);
var preference = new MemberPreferenceRequest
{
UserId = "99",
Preference = PreferenceType.ENotification,
Value = "True"
};
var result = await _memberPreferenceService.SaveMemberPreferenceAsync(preference);
Assert.NotNull(result);
saved = await _memberPreferenceService.GetMemberPreferencesAsync("99");
Assert.NotNull(saved);
Assert.IsNotEmpty(saved);
}
[Test]
public async Task UnifiedOptIn_Flow()
{
var saved = await _memberPreferenceService.GetMemberPreferencesAsync("99");
Assert.NotNull(saved);
Assert.IsEmpty(saved);
_mockNotificationService
.Setup(x => x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>()));
_mockIntegrationService.Setup(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()))
.Verifiable();
var preference = new MemberOptinRequest
{
UserId = "99",
Email = "[email protected]",
Value = DeliveryPreference.Electronic,
LegalReference = "1.0.0"
};
await _memberPreferenceService.UpdateMemberOptinAsync(preference);
saved = await _memberPreferenceService.GetMemberPreferencesAsync("99");
Assert.NotNull(saved);
Assert.IsNotEmpty(saved);
_mockIntegrationService.Verify();
}
[Test]
public async Task UpdateMemberOptInAsync_Email_Ok()
{
_mockIntegrationService.Setup(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>())).Verifiable();
var request = new MemberOptinRequest
{
Email = "[email protected]",
Value = DeliveryPreference.Electronic,
UserId = "12",
LegalReference = ""
};
await _memberPreferenceService.UpdateMemberOptinAsync(request);
_mockIntegrationService.Verify(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()), Times.Once);
}
[Test]
public async Task UpdateMemberOptInAsync_Paper_Ok()
{
_mockIntegrationService.Setup(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()))
.Verifiable();
var agreement = new Agreement
{
UserId = "12",
ByOrgNbr = 0,
PersonNumber = 111,
AgreementNumber = 54321
};
var accounts = new List<AgreementAccount>
{
new AgreementAccount
{
AccountNumber = 123,
TaxReportForPersonNumber = 111,
OvrDeliveryMethCD = "WWW",
AccountOwner = new AgreementAccountOwner
{
AccountNumber = 123,
PersonNumber = 111,
AgreementNumber = 54321
}
}
};
_mockCoreApiWrapperService.Setup(x => x.GetAgreementByUserId("12")).ReturnsAsync(agreement).Verifiable();
_mockCoreApiWrapperService.Setup(x => x.GetAgreementAccountsByUserId("12")).ReturnsAsync(accounts)
.Verifiable();
var request = new MemberOptinRequest
{
Value = DeliveryPreference.Paper,
UserId = "12",
LegalReference = ""
};
await _memberPreferenceService.UpdateMemberOptinAsync(request);
_mockIntegrationService.Verify(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()), Times.Once);
_mockCoreApiWrapperService.Verify();
_mockCoreApiWrapperService.Verify(x => x.UpdateAgreementAccountsDeliveryMethod(It.Is<List<long>>(l => l.Contains(123)), It.Is<string>(d => d.Equals("PRNT")), It.Is<string>(u => u.Equals("12"))), Times.Once());
}
[Test]
public async Task UpdateMemberOptInAsync_Electronic_Ok()
{
_mockIntegrationService.Setup(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()))
.Verifiable();
var agreement = new Agreement
{
UserId = "12",
ByOrgNbr = 0,
PersonNumber = 111,
AgreementNumber = 54321
};
var accounts = new List<AgreementAccount>
{
new AgreementAccount
{
AccountNumber = 123,
TaxReportForPersonNumber = 111,
OvrDeliveryMethCD = "PRNT",
AccountOwner = new AgreementAccountOwner
{
AccountNumber = 123,
PersonNumber = 111,
AgreementNumber = 54321
}
}
};
_mockCoreApiWrapperService.Setup(x => x.GetAgreementByUserId("12")).ReturnsAsync(agreement).Verifiable();
_mockCoreApiWrapperService.Setup(x => x.GetAgreementAccountsByUserId("12")).ReturnsAsync(accounts).Verifiable();
var request = new MemberOptinRequest
{
Email = "[email protected]",
Value = DeliveryPreference.Electronic,
UserId = "12",
LegalReference = ""
};
await _memberPreferenceService.UpdateMemberOptinAsync(request);
_mockIntegrationService.Verify(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()), Times.Once);
_mockCoreApiWrapperService.Verify();
_mockCoreApiWrapperService.Verify(x => x.UpdateAgreementAccountsDeliveryMethod(It.Is<List<long>>(l => l.Contains(123)), It.Is<string>(d => d.Equals("WWW")), It.Is<string>(u => u.Equals("12"))), Times.Once());
}
[Test]
public async Task UpdateMemberOptInAsync_Organization_Electronic_Ok()
{
_mockIntegrationService.Setup(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>())).Verifiable();
var agreement = new Agreement
{
UserId = "12",
PersonNumber = 111,
ByOrgNbr = 112,
AgreementNumber = 54321
};
var organizationAccounts = new List<AgreementAccount>
{
new AgreementAccount
{
AccountNumber = 123,
TaxReportForOrgNumber = 112,
AccountOwner = new AgreementAccountOwner
{
AccountNumber = 123,
PersonNumber = 111,
AgreementNumber = 54321
}
},
new AgreementAccount
{
AccountNumber = 124,
TaxReportForOrgNumber = 112,
AccountOwner = new AgreementAccountOwner
{
AccountNumber = 124,
PersonNumber = 115,
AgreementNumber = 5432
}
},
new AgreementAccount
{
AccountNumber = 125,
TaxReportForOrgNumber = 112,
AccountOwner = new AgreementAccountOwner
{
AccountNumber = 125,
PersonNumber = 111,
AgreementNumber = 54321
}
}
};
_mockCoreApiWrapperService.Setup(x => x.GetAgreementByUserId("12")).ReturnsAsync(agreement).Verifiable();
_mockCoreApiWrapperService.Setup(x => x.GetAgreementAccountsByOrganizationId(112)).ReturnsAsync(organizationAccounts).Verifiable();
var request = new MemberOptinRequest
{
Email = "[email protected]",
Value = DeliveryPreference.Electronic,
UserId = "12",
LegalReference = ""
};
await _memberPreferenceService.UpdateMemberOptinAsync(request);
_mockIntegrationService.Verify(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()), Times.Once);
_mockCoreApiWrapperService.Verify();
_mockCoreApiWrapperService.Verify(x => x.UpdateAgreementAccountsDeliveryMethod(It.Is<List<long>>(l => l.Contains(123) && l.Contains(125)), It.Is<string>(d => d.Equals("WWW")), It.Is<string>(u => u.Equals("12"))), Times.Once());
}
[Test]
public void UpdateMemberOptInAsync_Email_RequiresValidEmail()
{
_mockIntegrationService.Setup(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()))
.Verifiable();
var request = new MemberOptinRequest
{
Email = "gmail",
Value = DeliveryPreference.Electronic,
UserId = "12",
LegalReference = ""
};
Assert.ThrowsAsync<FormatException>(async () =>
{
await _memberPreferenceService.UpdateMemberOptinAsync(request);
});
_mockIntegrationService.Verify(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()), Times.Never);
}
[Test]
public void UpdateMemberOptInAsync_Email_RequiresEmail()
{
_mockIntegrationService.Setup(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()))
.Verifiable();
var request = new MemberOptinRequest()
{
Value = DeliveryPreference.Electronic,
UserId = "12",
LegalReference = ""
};
Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await _memberPreferenceService.UpdateMemberOptinAsync(request);
});
_mockIntegrationService.Verify(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()), Times.Never);
}
[Test]
public async Task UpdateMemberOptInAsync_DoesNothing_If_Invalid_Value_Ok()
{
_mockIntegrationService.Setup(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()))
.Verifiable();
var request = new MemberOptinRequest()
{
Email = "[email protected]",
Value = DeliveryPreference.Electronic,
UserId = "12",
LegalReference = ""
};
await _memberPreferenceService.UpdateMemberOptinAsync(request);
_mockIntegrationService.Verify(x => x.NotifyListeners(It.IsAny<MemberOptInSettings>()), Times.Once);
}
[TestCase(PreferenceType.EStatements, "Paper", false)]
[TestCase(PreferenceType.EStatements, "Email", true)]
[TestCase(PreferenceType.EStatementsEmail, "[email protected]", false)]
[TestCase(PreferenceType.EStatements, "[email protected]", true)]
[TestCase(PreferenceType.ENotificationsEmail, "[email protected]", false)]
[TestCase(PreferenceType.ENotification, "[email protected]", true)]
[TestCase(PreferenceType.UnifiedOptInEmail, "[email protected]", false)]
[TestCase(PreferenceType.UnifiedOptIn, "Electronic", false)]
public void IsExternalUpdateNecessary_NoUnified_OK(PreferenceType pref, string requestValue, bool assertion)
{
var settings = new MemberOptInSettings()
{
ENotifications = "Paper",
EStatements = "Paper",
EStatementsEmail = "[email protected]",
ENotificationsEmail = "[email protected]",
};
var request = new MemberPreferenceRequest()
{
Preference = pref,
Value = requestValue
};
Assert.AreEqual(assertion, _memberPreferenceService.IsExternalUpdateNecessary(settings, request));
}
[TestCase(PreferenceType.EStatements, "Paper", false)]
[TestCase(PreferenceType.EStatements, "Email", true)]
[TestCase(PreferenceType.EStatementsEmail, "[email protected]", false)]
[TestCase(PreferenceType.EStatements, "[email protected]", true)]
[TestCase(PreferenceType.ENotificationsEmail, "[email protected]", false)]
[TestCase(PreferenceType.ENotification, "[email protected]", true)]
[TestCase(PreferenceType.UnifiedOptInEmail, "[email protected]", false)]
[TestCase(PreferenceType.UnifiedOptInEmail, "[email protected]", true)]
[TestCase(PreferenceType.UnifiedOptIn, "Electronic", true)]
[TestCase(PreferenceType.UnifiedOptIn, "Paper", false)]
public void IsExternalUpdateNecessary_HasUnified_OK(PreferenceType pref, string requestValue, bool assertion)
{
var settings = new MemberOptInSettings()
{
ENotifications = "Paper",
EStatements = "Paper",
EStatementsEmail = "[email protected]",
ENotificationsEmail = "[email protected]",
UnifiedOptInEmail = "[email protected]",
UniversalOptIn = "Paper"
};
var request = new MemberPreferenceRequest()
{
Preference = pref,
Value = requestValue
};
Assert.AreEqual(assertion, _memberPreferenceService.IsExternalUpdateNecessary(settings, request));
}
[Test]
public async Task SaveMemberPreferencesDefault_OK()
{
var paperDefault =
new MemberPreferenceRequest()
{
UserId = "100",
Preference = PreferenceType.UnifiedOptIn,
Value = "Paper",
LegalReference = "test",
};
var result =
await _memberPreferenceService.SaveMemberPreferenceDefaultAsync(paperDefault, "1337",
UserType.Associate,
DateTime.Parse("2021-02-12"));
Assert.NotNull(result);
Assert.AreEqual("1337", result.LastUpdatedBy);
Assert.AreEqual(DateTime.Parse("2021-02-12"), result.LastUpdated);
Assert.AreEqual(UserType.Associate, result.LastUpdatedByType);
}
[Test]
public void SaveMemberPreferences_Null_ThrowsArgumentException()
{
Assert.ThrowsAsync<ArgumentException>(async () =>
await _memberPreferenceService.SaveMemberPreferencesAsync(null));
}
[Test]
public void SaveMemberPreferences_Empty_ThrowsArgumentException()
{
Assert.ThrowsAsync<ArgumentException>(async () =>
await _memberPreferenceService.SaveMemberPreferencesAsync(new List<MemberPreferenceRequest>()));
}
[Test]
public void SaveMemberPreferences_HasPendingXdiUpdate_PendingUpdatesException()
{
var preference = new List<MemberPreferenceRequest>
{
new MemberPreferenceRequest
{
Preference = PreferenceType.UnifiedOptIn,
Value = "Paper",
UserId = "222"
}
};
_xdiBatchItemServiceMock.Setup(x => x.DoesMemberHavePendingXdiChange("222")).ReturnsAsync(true).Verifiable();
Assert.ThrowsAsync<Exception>(async () => await _memberPreferenceService.SaveMemberPreferencesAsync(preference));
_xdiBatchItemServiceMock.Verify();
}
[Test]
public async Task SaveMemberPreferencesDefault_NoChange_OK()
{
await _memberPreferenceService.SaveMemberPreferencesAsync(new List<MemberPreferenceRequest>()
{
new MemberPreferenceRequest()
{
UserId = "100",
Preference = PreferenceType.UnifiedOptIn,
Value = "Electronic",
LegalReference = "test",
},
new MemberPreferenceRequest()
{
UserId = "100",
Preference = PreferenceType.EStatements,
Value = "Electronic",
LegalReference = "test",
},
}
);
var emailRequests =
new MemberPreferenceRequest()
{
UserId = "100",
Preference = PreferenceType.UnifiedOptIn,
Value = "Electronic",
LegalReference = "test",
};
var result =
await _memberPreferenceService.SaveMemberPreferenceDefaultAsync(emailRequests, "1337", UserType.System,
DateTime.Parse("2021-02-12"));
Assert.NotNull(result);
Assert.AreEqual("Electronic", result.UniversalOptIn);
Assert.AreEqual("Electronic", result.EStatements);
Assert.AreNotEqual(DateTime.Parse("2021-02-12"), result.LastUpdatedBy);
Assert.AreNotEqual("1337", result.LastUpdated);
Assert.AreEqual(UserType.System, result.LastUpdatedByType);
}
[Test]
public void UpdateMemberOptInAsync_BadEmail()
{
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Electronic,
Email = "234@",
LegalReference = "none"
};
Assert.ThrowsAsync<FormatException>(async () =>
await _memberPreferenceService.UpdateMemberOptinAsync(request));
request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Electronic,
LegalReference = "none"
};
Assert.ThrowsAsync<ArgumentNullException>(async () =>
await _memberPreferenceService.UpdateMemberOptinAsync(request));
}
[Test]
public async Task SendOptInChangeNotification_Unknown_To_Paper()
{
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Paper,
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, null);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>()), Times.Never);
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>()), Times.Never);
}
[Test]
public async Task SendOptInChangeNotification_Unknown_To_Paper_IgnoresRequestEmail()
{
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Paper,
Email = "[email protected]",
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, null);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>()), Times.Never);
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>()), Times.Never);
}
[Test]
public async Task SendOptInChangeNotification_Email_To_Paper()
{
var existing = new MemberOptInSettings()
{
EStatements = DeliveryPreference.Electronic,
EStatementsEmail = "[email protected]",
ENotifications = DeliveryPreference.Electronic,
ENotificationsEmail = "[email protected]",
UnifiedOptInEmail = "[email protected]",
UniversalOptIn = DeliveryPreference.Electronic
};
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Paper,
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, existing);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>()), Times.Never);
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.Is<List<string>>(emails => emails.Count == 1)));
}
[Test]
public async Task SendOptInChangeNotification_Email_To_Paper_IgnoreRequestEmail()
{
var existing = new MemberOptInSettings()
{
EStatements = DeliveryPreference.Electronic,
EStatementsEmail = "[email protected]",
ENotifications = DeliveryPreference.Electronic,
ENotificationsEmail = "[email protected]",
UnifiedOptInEmail = "[email protected]",
UniversalOptIn = DeliveryPreference.Electronic
};
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Paper,
Email = "[email protected]",
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, existing);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>()), Times.Never);
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.Is<List<string>>(emails => emails.Count == 1)));
}
[Test]
public async Task SendOptInChangeNotification_Paper_To_Email()
{
var existing = new MemberOptInSettings()
{
EStatements = DeliveryPreference.Electronic,
EStatementsEmail = "[email protected]",
ENotifications = DeliveryPreference.Electronic,
ENotificationsEmail = "[email protected]",
UnifiedOptInEmail = "[email protected]",
UniversalOptIn = DeliveryPreference.Paper
};
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Electronic,
Email = "[email protected]",
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, existing);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.Is<List<string>>(emails => emails.Count == 1),
It.IsAny<MemberOptinRequest>()));
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>()), Times.Never);
}
[Test]
public async Task SendOptInChangeNotification_Unknown_To_Email()
{
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Electronic,
Email = "[email protected]",
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, null);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.Is<List<string>>(emails => emails.Count == 1),
It.IsAny<MemberOptinRequest>()));
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>()), Times.Never);
}
[Test]
public async Task SendOptInChangeNotification_Email_To_Email_NoChange()
{
var existing = new MemberOptInSettings()
{
EStatements = DeliveryPreference.Electronic,
EStatementsEmail = "[email protected]",
ENotifications = DeliveryPreference.Electronic,
ENotificationsEmail = "[email protected]",
UnifiedOptInEmail = "[email protected]",
UniversalOptIn = DeliveryPreference.Electronic
};
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Electronic,
Email = "[email protected]",
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, existing);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>()), Times.Never);
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>()), Times.Never);
}
[Test]
public async Task SendOptInChangeNotification_Email_To_Email_IsChange()
{
var existing = new MemberOptInSettings()
{
EStatements = DeliveryPreference.Electronic,
EStatementsEmail = "[email protected]",
ENotifications = DeliveryPreference.Electronic,
ENotificationsEmail = "[email protected]",
UnifiedOptInEmail = "[email protected]",
UniversalOptIn = DeliveryPreference.Electronic
};
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Electronic,
Email = "[email protected]",
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, existing);
_mockNotificationService.Verify(x =>
x.SendEmailChangeNotifications(It.Is<List<string>>(emails => emails.Count == 2),
It.IsAny<MemberOptinRequest>()));
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>()), Times.Never);
}
[TestCase("[email protected]", "[email protected]", 3)]
[TestCase("[email protected]", "[email protected]", 3)]
[TestCase("[email protected]", "[email protected]", 3)]
[TestCase("[email protected]", "[email protected]", 3)]
[TestCase(null, "[email protected]", 2)]
[TestCase("[email protected]", null, 2)]
public async Task SendOptInChangeNotification_Historic_To_Email(string eStatementsEmail,
string eNotificationsEmail, int optInEmailCount)
{
var existing = new MemberOptInSettings()
{
EStatements = DeliveryPreference.Electronic,
EStatementsEmail = eStatementsEmail,
ENotifications = DeliveryPreference.Electronic,
ENotificationsEmail = eNotificationsEmail
};
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Electronic,
Email = "[email protected]",
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, existing);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.Is<List<string>>(emails => emails.Count == optInEmailCount),
It.IsAny<MemberOptinRequest>()));
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>()), Times.Never);
}
[TestCase("[email protected]", "[email protected]", 2)]
[TestCase("[email protected]", "[email protected]", 2)]
[TestCase("[email protected]", "[email protected]", 2)]
[TestCase("[email protected]", "[email protected]", 2)]
[TestCase(null, "[email protected]", 1)]
[TestCase("[email protected]", null, 1)]
public async Task SendOptInChangeNotification_Historic_To_Paper(string eStatementsEmail,
string eNotificationsEmail, int optOutEmailCount)
{
var existing = new MemberOptInSettings
{
EStatements = DeliveryPreference.Electronic,
EStatementsEmail = eStatementsEmail,
ENotifications = DeliveryPreference.Electronic,
ENotificationsEmail = eNotificationsEmail
};
var request = new MemberOptinRequest()
{
UserId = "100",
Value = DeliveryPreference.Paper,
LegalReference = "none"
};
_mockNotificationService.Setup(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>())).Verifiable();
_mockNotificationService.Setup(x =>
x.SendOptOutNotifications(It.IsAny<List<string>>())).Verifiable();
await _memberPreferenceService.SendOptInChangeNotifications(request, existing);
_mockNotificationService.Verify(x =>
x.SendOptInNotifications(It.IsAny<List<string>>(), It.IsAny<MemberOptinRequest>()), Times.Never);
_mockNotificationService.Verify(x =>
x.SendOptOutNotifications(It.Is<List<string>>(emails => emails.Count == optOutEmailCount)));
}
[TestCase(DeliveryPreference.Paper, "[email protected]", DeliveryPreference.Electronic,
"[email protected]", 1)]
[TestCase(DeliveryPreference.Electronic, "[email protected]", DeliveryPreference.Paper,
"[email protected]", 1)]
[TestCase(DeliveryPreference.Electronic, "[email protected]", DeliveryPreference.Electronic,
"[email protected]", 2)]
[TestCase(DeliveryPreference.Electronic, "", DeliveryPreference.Electronic, "[email protected]", 1)]
[TestCase(DeliveryPreference.Electronic, "[email protected]", DeliveryPreference.Electronic, null, 1)]
[TestCase(DeliveryPreference.Paper, "[email protected]", DeliveryPreference.Paper,
"[email protected]", 0)]
public void TryAddHistoricEmails_Ok(string eNotificationsValue, string eNotificationsEmail,
string eStatementsValue, string eStatementsEmail, int assertCount)
{
var ogSettings = new MemberOptInSettings()
{
ENotifications = eNotificationsValue,
ENotificationsEmail = eNotificationsEmail,
EStatements = eStatementsValue,
EStatementsEmail = eStatementsEmail
};
var affectedEmails = new List<string>();
_memberPreferenceService.TryAddHistoricEmails(ogSettings, affectedEmails);
Assert.AreEqual(assertCount, affectedEmails.Count);
}
}
}
@@ -0,0 +1,166 @@
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LCU.API.Internal.MemberPreferencesApi.Services;
using LCU.Library.Internal.MemberPreferencesApiModels.Entities;
using LCU.Library.Internal.MemberPreferencesApiModels.Enums;
using LCU.Library.Internal.CoreApiWrapperModel.CoreModels.Agreements;
using LCU.API.Internal.MemberPreferencesApiLib.Repositories;
using LCU.API.Internal.MemberPreferencesApi.Services.XdiServices;
using LCU.API.Internal.MemberPreferencesApi.MicroApiServices;
namespace LCU.API.Internal.MemberPreferencesApi.UnitTests.Services
{
public class UnifiedOptInServiceTest
{
private OptinService _service;
private Mock<IUnifiedOptInRepository> _mockRepository;
private Mock<IXdiBatchService> _mockXdiBatchItemService;
private Mock<ICoreApiWrapperService> _mockCoreApiWrapperService;
private Mock<IMemberPreferenceService> _mockMemberPreferenceService;
[SetUp]
public void Setup()
{
_mockRepository = new Mock<IUnifiedOptInRepository>();
_mockXdiBatchItemService = new Mock<IXdiBatchService>();
_mockCoreApiWrapperService = new Mock<ICoreApiWrapperService>();
_mockMemberPreferenceService = new Mock<IMemberPreferenceService>();
_service = new OptinService(_mockRepository.Object, _mockXdiBatchItemService.Object, _mockMemberPreferenceService.Object, _mockCoreApiWrapperService.Object);
}
[Test]
public async Task Get_OptIn_OK()
{
var testSettings1 = new MemberOptInSettings
{
UserId = "1",
UniversalOptIn = "Email"
};
_mockRepository.Setup(x => x.GetMemberOptInSettings("1")).ReturnsAsync(testSettings1).Verifiable();
// act
var result = await _service.GetMemberOptInSettings("1");
Assert.NotNull(result);
Assert.AreEqual("1", result.UserId);
Assert.AreEqual("Email", result.UniversalOptIn);
_mockRepository.Verify();
}
[Test]
public async Task GetMemberOptInAgreementInformation_OptIn_OK()
{
var agreements = new List<Agreement>
{
new Agreement
{
UserId = "1"
},
new Agreement
{
UserId = "2"
}
};
var testSetting = new MemberOptInSettings
{
UserId = "1",
UniversalOptIn = "Email"
};
_mockCoreApiWrapperService.Setup(x => x.GetAgreementsByAccountId(123)).ReturnsAsync(agreements).Verifiable();
_mockRepository.Setup(x => x.GetMemberOptInSettings("1")).ReturnsAsync(testSetting).Verifiable();
_mockRepository.Setup(x => x.GetMemberOptInSettings("2")).ReturnsAsync(testSetting).Verifiable();
// act
var result = await _service.GetMemberOptInAgreementInformationByAccountId(123);
Assert.NotNull(result);
Assert.IsNotEmpty(result);
_mockCoreApiWrapperService.Verify();
_mockRepository.Verify();
}
[TestCase(true)]
[TestCase(false)]
public async Task TransformMemberOptInSettingsForClient_OK(bool hasPending)
{
var testSettings1 = new MemberOptInSettings
{
Id = 10,
UserId = "100",
EStatements = DeliveryPreference.Microfiche,
ENotifications = DeliveryPreference.Paper,
UniversalOptIn = DeliveryPreference.Electronic,
LegalVersion = "2021/01/01",
LegalDate = DateTime.Parse("2021/01/01"),
UnifiedOptInEmail = "[email protected]",
EStatementsEmail = "[email protected]",
ENotificationsEmail = "[email protected]",
Created = DateTime.Parse("2021/01/01"),
CreatedBy = "TestUser",
CreatedByType = UserType.Associate,
LastUpdated = DateTime.Parse("2021/02/01"),
LastUpdatedBy = "TestMember",
LastUpdatedByType = UserType.Member,
};
_mockXdiBatchItemService.Setup(x => x.DoesMemberHavePendingXdiChange(It.IsAny<string>()))
.ReturnsAsync(hasPending);
// act
var transformation = await _service.TransformMemberOptInSettingsForClient(testSettings1);
Assert.NotNull(transformation);
var result = transformation.MemberOptinSettings;
Assert.AreEqual(10, result.Id);
Assert.AreEqual("100", result.UserId);
Assert.AreEqual(DeliveryPreference.Microfiche, result.EStatements);
Assert.AreEqual(DeliveryPreference.Paper, result.ENotifications);
Assert.AreEqual(DeliveryPreference.Electronic, result.UniversalOptIn);
Assert.AreEqual("2021/01/01", result.LegalVersion);
Assert.AreEqual(DateTime.Parse("2021/01/01"), result.LegalDate);
Assert.AreEqual("[email protected]", result.UnifiedOptInEmail);
Assert.AreEqual("[email protected]", result.EStatementsEmail);
Assert.AreEqual("[email protected]", result.ENotificationsEmail);
Assert.AreEqual(DateTime.Parse("2021/01/01"), result.Created);
Assert.AreEqual("TestUser", result.CreatedBy);
Assert.AreEqual(UserType.Associate, result.CreatedByType);
Assert.AreEqual(DateTime.Parse("2021/02/01"), result.LastUpdated);
Assert.AreEqual("TestMember", result.LastUpdatedBy);
Assert.AreEqual(UserType.Member, result.LastUpdatedByType);
Assert.AreEqual(hasPending, transformation.HasPendingUpdates);
}
[Test]
public async Task TransformMemberOptInSettingsForClient_List_OK()
{
var testSettings1 = new List<MemberOptInSettings>
{
new MemberOptInSettings
{
UserId = "9",
UniversalOptIn = "Email"
},
new MemberOptInSettings
{
UserId = "10",
UniversalOptIn = "Paper"
},
};
_mockXdiBatchItemService.Setup(x => x.DoesMemberHavePendingXdiChange("9"))
.ReturnsAsync(true).Verifiable();
_mockXdiBatchItemService.Setup(x => x.DoesMemberHavePendingXdiChange("10"))
.ReturnsAsync(false).Verifiable();
// act
var result = await _service.TransformMemberOptInSettingsForClient(testSettings1);
_mockXdiBatchItemService.Verify();
Assert.NotNull(result);
Assert.IsNotEmpty(result);
Assert.AreEqual(result.Count, 2);
Assert.True(result.ToList().Exists(x => x.HasPendingUpdates));
Assert.True(result.ToList().Exists(x => !x.HasPendingUpdates));
}
}
}
@@ -0,0 +1,407 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LCU.API.Internal.MemberPreferencesApi.Configuration;
using LCU.Library.Internal.MemberPreferencesApiModels.Entities;
using LCU.Library.Internal.MemberPreferencesApiModels.Enums;
using LCU.Library.Internal.LcuMassTransitModels;
using LCU.API.Internal.MemberPreferencesApiLib.Repositories;
using LCU.API.Internal.MemberPreferencesApi.Services.XdiServices;
using LCU.API.Internal.MemberPreferencesApi.MicroApiServices;
using Moq;
using Newtonsoft.Json;
using NUnit.Framework;
using LCU.API.Internal.MemberPreferencesApi.Models;
namespace LCU.API.Internal.MemberPreferencesApi.UnitTests.Services
{
public class XdiBatchItemServiceTest
{
private IXdiBatchService _xdiBatchItemService;
private Mock<IXdiBatchItemsRepository> _mockBatchItemsRepository;
private Mock<IUnitOfWork> _mockUnitOfWork;
private XdiSftpApiConfiguration _ftpConfiguration;
private Mock<IUnifiedOptInRepository> _mockUnifiedOptinRepository;
private Mock<IMemberPreferenceRepository> _mockMemberPreferenceRepository;
private Mock<IFtpApiService> _mockFtpApiService;
private ConnectionConfiguration _connectionConfiguration;
private ReceiveEndpointConfiguration _completionReceiveEndpoint;
private ReceiveEndpointConfigurations _endpointConfiguration;
[SetUp]
public void Setup()
{
_mockBatchItemsRepository = new Mock<IXdiBatchItemsRepository>();
_mockUnitOfWork = new Mock<IUnitOfWork>();
_ftpConfiguration = new XdiSftpApiConfiguration();
_mockUnifiedOptinRepository = new Mock<IUnifiedOptInRepository>();
_mockMemberPreferenceRepository = new Mock<IMemberPreferenceRepository>();
_mockFtpApiService = new Mock<IFtpApiService>();
_endpointConfiguration = new ReceiveEndpointConfigurations();
_completionReceiveEndpoint = _endpointConfiguration.XdiBatchConfirmEndpoint;
_xdiBatchItemService = new XdiBatchService(_mockBatchItemsRepository.Object, _mockUnitOfWork.Object,
_ftpConfiguration, _mockUnifiedOptinRepository.Object, _mockMemberPreferenceRepository.Object,
_connectionConfiguration, _endpointConfiguration, _mockFtpApiService.Object);
}
[Test]
public async Task Test_Item_Exists()
{
var existing = new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "99"
};
_mockBatchItemsRepository.Setup(x => x.FindExistingItem(existing.UserId, existing.BatchState))
.ReturnsAsync(existing);
_mockBatchItemsRepository.Setup(x => x.Update(existing)).Verifiable();
_mockBatchItemsRepository.Setup(x => x.SaveAsync(existing)).Verifiable();
_mockUnitOfWork.Setup(x => x.CompleteAsync()).Verifiable();
XdiBatchItem testItem = new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "99"
};
await _xdiBatchItemService.AddXdiBatchItem(testItem);
_mockBatchItemsRepository.Verify(x => x.FindExistingItem(existing.UserId, existing.BatchState),
Times.Once);
_mockBatchItemsRepository.Verify(x => x.Update(existing), Times.Once);
_mockBatchItemsRepository.Verify(x => x.SaveAsync(existing), Times.Never);
_mockUnitOfWork.Verify(x => x.CompleteAsync(), Times.Once);
}
[Test]
public async Task Test_Item_New()
{
_mockBatchItemsRepository.Setup(x => x.FindExistingItem(It.IsAny<string>(), It.IsAny<BatchState>()))
.ReturnsAsync((XdiBatchItem)null);
_mockBatchItemsRepository.Setup(x => x.Update(It.IsAny<XdiBatchItem>())).Verifiable();
_mockBatchItemsRepository.Setup(x => x.SaveAsync(It.IsAny<XdiBatchItem>())).Verifiable();
_mockUnitOfWork.Setup(x => x.CompleteAsync()).Verifiable();
XdiBatchItem testItem = new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "99"
};
await _xdiBatchItemService.AddXdiBatchItem(testItem);
_mockBatchItemsRepository.Verify(x => x.FindExistingItem(It.IsAny<string>(), It.IsAny<BatchState>()),
Times.Once);
_mockBatchItemsRepository.Verify(x => x.Update(It.IsAny<XdiBatchItem>()), Times.Never);
_mockBatchItemsRepository.Verify(x => x.SaveAsync(It.IsAny<XdiBatchItem>()), Times.Once);
_mockUnitOfWork.Verify(x => x.CompleteAsync(), Times.Once);
}
[Test]
public async Task Test_Create_Batch_Files()
{
IReadOnlyCollection<XdiBatchItem> items = new List<XdiBatchItem>()
{
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "99"
},
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "100"
},
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "101"
},
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "102"
},
//This is pending and we will process it again
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.TransferPending,
LastUpdated = DateTime.Now,
UserId = "103"
}
};
// Should be one of each type of change, resulting in a single line batch file for all types.
var settings = new List<MemberOptInSettings>()
{
new MemberOptInSettings()
{
Id = 1000,
UniversalOptIn = DeliveryPreference.Paper,
ENotifications = DeliveryPreference.Electronic,
EStatements = DeliveryPreference.Electronic,
UnifiedOptInEmail = "[email protected]",
ENotificationsEmail = "[email protected]",
EStatementsEmail = "[email protected]",
LastUpdated = DateTime.Now,
LegalDate = DateTime.Now,
LegalVersion = "1.2.3",
UserId = "99",
CreatedByType = UserType.Associate,
LastUpdatedByType = UserType.System,
CreatedBy = "test",
Created = DateTime.Now,
LastUpdatedBy = "test"
},
new MemberOptInSettings()
{
Id = 1001,
UniversalOptIn = DeliveryPreference.Paper,
ENotifications = null,
EStatements = DeliveryPreference.Electronic,
UnifiedOptInEmail = "[email protected]",
ENotificationsEmail = null,
EStatementsEmail = "[email protected]",
UserId = "100"
},
new MemberOptInSettings()
{
Id = 1002,
UniversalOptIn = DeliveryPreference.Electronic,
ENotifications = DeliveryPreference.Paper,
EStatements = DeliveryPreference.Paper,
UnifiedOptInEmail = "[email protected]",
ENotificationsEmail = "[email protected]",
EStatementsEmail = "[email protected]",
UserId = "101"
},
new MemberOptInSettings()
{
Id = 1003,
UniversalOptIn = DeliveryPreference.Electronic,
ENotifications = null,
EStatements = DeliveryPreference.Paper,
UnifiedOptInEmail = "[email protected]",
ENotificationsEmail = null,
EStatementsEmail = null,
UserId = "102"
},
new MemberOptInSettings()
{
Id = 1004,
UniversalOptIn = DeliveryPreference.Electronic,
ENotifications = DeliveryPreference.Electronic,
EStatements = DeliveryPreference.Electronic,
UnifiedOptInEmail = "[email protected]",
ENotificationsEmail = "[email protected]",
EStatementsEmail = "[email protected]",
UserId = "103"
}
};
_mockBatchItemsRepository.Setup(x => x.GetXdiBatchItems()).ReturnsAsync(items);
foreach (var setting in settings)
{
_mockUnifiedOptinRepository.Setup(x => x.GetMemberOptInSettings(setting.UserId))
.ReturnsAsync(setting);
}
_mockBatchItemsRepository.Setup(x => x.Update(It.IsAny<XdiBatchItem>())).Verifiable();
_mockBatchItemsRepository.Setup(x => x.Delete(It.IsAny<XdiBatchItem>())).Verifiable();
_mockUnitOfWork.Setup(x => x.CompleteAsync(It.IsAny<string>(), It.IsAny<DateTime>(), It.IsAny<UserType>()))
.Verifiable();
}
[Test]
public async Task CreateFtpQueryPayload_Ok()
{
var testFile = new XdiBatchFile
{
Data = new List<XdiBatchFileRow>
{
new XdiBatchFileRow {UserId = "100", Email = "[email protected]",},
new XdiBatchFileRow {UserId = "101", Email = "[email protected]",},
new XdiBatchFileRow {UserId = "102", Email = "[email protected]",},
new XdiBatchFileRow {UserId = "103", Email = "[email protected]",}
}
};
IReadOnlyCollection<XdiBatchItem> items = new List<XdiBatchItem>()
{
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "99"
},
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "100"
},
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "101"
},
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.New,
LastUpdated = DateTime.Now,
UserId = "102"
},
//This is pending and we will process it again
new XdiBatchItem()
{
Created = DateTime.Now,
BatchState = BatchState.TransferPending,
LastUpdated = DateTime.Now,
UserId = "103"
}
};
_mockUnifiedOptinRepository
.Setup(x => x.GetMemberOptInSettingsNoTracking("100")).ReturnsAsync(new MemberOptInSettings
{
UserId = "100",
UniversalOptIn = DeliveryPreference.Electronic,
UnifiedOptInEmail = "[email protected]"
});
_mockUnifiedOptinRepository
.Setup(x => x.GetMemberOptInSettingsNoTracking("101")).ReturnsAsync(new MemberOptInSettings
{
UserId = "101",
UniversalOptIn = DeliveryPreference.Paper
});
_mockUnifiedOptinRepository
.Setup(x => x.GetMemberOptInSettingsNoTracking("102")).ReturnsAsync(new MemberOptInSettings
{
UserId = "102",
UniversalOptIn = DeliveryPreference.Microfiche
});
_mockUnifiedOptinRepository
.Setup(x => x.GetMemberOptInSettingsNoTracking("103")).ReturnsAsync(new MemberOptInSettings
{
UserId = "103",
UniversalOptIn = DeliveryPreference.Hold
});
var results = await _xdiBatchItemService.CreateFtpPayload(testFile);
Assert.AreEqual(4, results.Count);
Assert.True(results.Exists(x => x.UserId == "100" && x.Value == "[email protected]"));
Assert.True(results.Exists(x => x.UserId == "101" && x.Value == DeliveryPreference.Paper));
Assert.True(results.Exists(x => x.UserId == "102" && x.Value == DeliveryPreference.Paper));
Assert.True(results.Exists(x => x.UserId == "103" && x.Value == DeliveryPreference.Paper));
}
[Test]
public async Task CreateFtpQueryPayload_No_Result_Ok()
{
var testFile = new XdiBatchFile
{
Data = new List<XdiBatchFileRow>
{
new XdiBatchFileRow {UserId = "100", Email = "[email protected]",},
new XdiBatchFileRow {UserId = "101", Email = "[email protected]",},
new XdiBatchFileRow {UserId = "102", Email = "[email protected]",},
new XdiBatchFileRow {UserId = "103", Email = "[email protected]",}
}
};
_mockUnifiedOptinRepository
.Setup(x => x.GetMemberOptInSettingsNoTracking("100")).ReturnsAsync(new MemberOptInSettings
{
UserId = "100",
UniversalOptIn = DeliveryPreference.Paper
}).Verifiable();
_mockUnifiedOptinRepository
.Setup(x => x.GetMemberOptInSettingsNoTracking(It.Is<string>(userId => int.Parse(userId) > 100)))
.Returns(Task.FromResult<MemberOptInSettings>(null));
var results = await _xdiBatchItemService.CreateFtpPayload(testFile);
Assert.AreEqual(1, results.Count);
Assert.True(results.Exists(x => x.UserId == "100" && x.Value == DeliveryPreference.Paper));
}
[Test]
public async Task MarkPendingSuccessful_OK()
{
var payload = new List<FtpQueuePayloadItem>()
{
new FtpQueuePayloadItem()
{
UserId = "100",
Value = DeliveryPreference.Paper
},
new FtpQueuePayloadItem()
{
UserId = "101",
Value = "[email protected]"
}
};
var payloadString = JsonConvert.SerializeObject(payload);
var response = new LCU.Library.Internal.ApiResponse.Models.Response()
{
ResponsePayload = payloadString,
Successful = true
};
_mockMemberPreferenceRepository.Setup(x => x.SaveMemberPreferenceAsync(It.IsAny<MemberPreference>()))
.Verifiable();
_mockMemberPreferenceRepository
.Setup(x => x.BulkSaveMemberPreferenceAsync(It.IsAny<List<MemberPreference>>())).Verifiable();
_mockUnifiedOptinRepository.Setup(x => x.GetOrCreateMemberOptinSettings(It.IsAny<string>()))
.ReturnsAsync(new MemberOptInSettings());
_mockBatchItemsRepository.Setup(x => x.MarkPendingSuccessful(It.IsAny<List<string>>())).ReturnsAsync(true)
.Verifiable();
var result = await _xdiBatchItemService.MarkPendingSuccessful(response);
Assert.True(result);
_mockBatchItemsRepository.Verify(x =>
x.MarkPendingSuccessful(It.Is<List<string>>(list =>
list.Contains("100") && list.Contains("101"))));
_mockMemberPreferenceRepository.Verify(x => x.SaveMemberPreferenceAsync(It.Is<MemberPreference>(preference =>
preference.UserId == "100" && preference.Value == DeliveryPreference.Paper)));
_mockMemberPreferenceRepository.Verify(x => x.BulkSaveMemberPreferenceAsync(It.Is<List<MemberPreference>>(
preferenceList =>
preferenceList.Exists(x => x.UserId == "101" && x.Value == DeliveryPreference.Electronic) &&
preferenceList.Exists(x => x.UserId == "101" && x.Value == "[email protected]"))));
_mockMemberPreferenceRepository.Verify(x =>
x.SaveMemberPreferenceAsync(It.IsAny<MemberPreference>()), Times.Once());
_mockMemberPreferenceRepository.Verify(x =>
x.BulkSaveMemberPreferenceAsync(It.IsAny<List<MemberPreference>>()), Times.Once());
}
}
}