Adhered to linting rules in hosted services implementations and tests.

This commit is contained in:
Andy Butland
2020-12-05 09:54:59 +01:00
parent 05dc597fc2
commit 201940290c
15 changed files with 339 additions and 229 deletions

View File

@@ -1,4 +1,8 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
@@ -13,6 +17,7 @@ using Umbraco.Core.Sync;
using Umbraco.Infrastructure.Configuration.Extensions;
using Umbraco.Infrastructure.HealthCheck;
using Umbraco.Web.HealthCheck;
using Umbraco.Web.HealthCheck.NotificationMethods;
namespace Umbraco.Infrastructure.HostedServices
{
@@ -31,6 +36,19 @@ namespace Umbraco.Infrastructure.HostedServices
private readonly ILogger<HealthCheckNotifier> _logger;
private readonly IProfilingLogger _profilingLogger;
/// <summary>
/// Initializes a new instance of the <see cref="HealthCheckNotifier"/> class.
/// </summary>
/// <param name="healthChecksSettings">The configuration for health check settings.</param>
/// <param name="healthChecks">The collection of healthchecks.</param>
/// <param name="notifications">The collection of healthcheck notification methods.</param>
/// <param name="runtimeState">Representation of the state of the Umbraco runtime.</param>
/// <param name="serverRegistrar">Provider of server registrations to the distributed cache.</param>
/// <param name="mainDom">Representation of the main application domain.</param>
/// <param name="scopeProvider">Provides scopes for database operations.</param>
/// <param name="logger">The typed logger.</param>
/// <param name="profilingLogger">The profiling logger.</param>
/// <param name="cronTabParser">Parser of crontab expressions.</param>
public HealthCheckNotifier(
IOptions<HealthChecksSettings> healthChecksSettings,
HealthCheckCollection healthChecks,
@@ -42,8 +60,9 @@ namespace Umbraco.Infrastructure.HostedServices
ILogger<HealthCheckNotifier> logger,
IProfilingLogger profilingLogger,
ICronTabParser cronTabParser)
: base(healthChecksSettings.Value.Notification.Period,
healthChecksSettings.Value.GetNotificationDelay(cronTabParser, DateTime.Now, DefaultDelay))
: base(
healthChecksSettings.Value.Notification.Period,
healthChecksSettings.Value.GetNotificationDelay(cronTabParser, DateTime.Now, DefaultDelay))
{
_healthChecksSettings = healthChecksSettings.Value;
_healthChecks = healthChecks;
@@ -88,25 +107,25 @@ namespace Umbraco.Infrastructure.HostedServices
// Ensure we use an explicit scope since we are running on a background thread and plugin health
// checks can be making service/database calls so we want to ensure the CallContext/Ambient scope
// isn't used since that can be problematic.
using (var scope = _scopeProvider.CreateScope())
using (IScope scope = _scopeProvider.CreateScope())
using (_profilingLogger.DebugDuration<HealthCheckNotifier>("Health checks executing", "Health checks complete"))
{
// Don't notify for any checks that are disabled, nor for any disabled just for notifications.
var disabledCheckIds = _healthChecksSettings.Notification.DisabledChecks
Guid[] disabledCheckIds = _healthChecksSettings.Notification.DisabledChecks
.Select(x => x.Id)
.Union(_healthChecksSettings.DisabledChecks
.Select(x => x.Id))
.Distinct()
.ToArray();
var checks = _healthChecks
IEnumerable<Core.HealthCheck.HealthCheck> checks = _healthChecks
.Where(x => disabledCheckIds.Contains(x.Id) == false);
var results = new HealthCheckResults(checks);
results.LogResults();
// Send using registered notification methods that are enabled.
foreach (var notificationMethod in _notifications.Where(x => x.Enabled))
foreach (IHealthCheckNotificationMethod notificationMethod in _notifications.Where(x => x.Enabled))
{
await notificationMethod.SendAsync(results);
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
@@ -24,7 +27,24 @@ namespace Umbraco.Infrastructure.HostedServices
private readonly IServerRegistrar _serverRegistrar;
private readonly IHttpClientFactory _httpClientFactory;
public KeepAlive(IRequestAccessor requestAccessor, IMainDom mainDom, IOptions<KeepAliveSettings> keepAliveSettings, ILogger<KeepAlive> logger, IProfilingLogger profilingLogger, IServerRegistrar serverRegistrar, IHttpClientFactory httpClientFactory)
/// <summary>
/// Initializes a new instance of the <see cref="KeepAlive"/> class.
/// </summary>
/// <param name="requestAccessor">Accessor for the current request.</param>
/// <param name="mainDom">Representation of the main application domain.</param>
/// <param name="keepAliveSettings">The configuration for keep alive settings.</param>
/// <param name="logger">The typed logger.</param>
/// <param name="profilingLogger">The profiling logger.</param>
/// <param name="serverRegistrar">Provider of server registrations to the distributed cache.</param>
/// <param name="httpClientFactory">Factory for <see cref="HttpClient" /> instances.</param>
public KeepAlive(
IRequestAccessor requestAccessor,
IMainDom mainDom,
IOptions<KeepAliveSettings> keepAliveSettings,
ILogger<KeepAlive> logger,
IProfilingLogger profilingLogger,
IServerRegistrar serverRegistrar,
IHttpClientFactory httpClientFactory)
: base(TimeSpan.FromMinutes(5), DefaultDelay)
{
_requestAccessor = requestAccessor;
@@ -79,8 +99,8 @@ namespace Umbraco.Infrastructure.HostedServices
}
var request = new HttpRequestMessage(HttpMethod.Get, keepAlivePingUrl);
var httpClient = _httpClientFactory.CreateClient();
await httpClient.SendAsync(request);
HttpClient httpClient = _httpClientFactory.CreateClient();
_ = await httpClient.SendAsync(request);
}
catch (Exception ex)
{

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -27,7 +30,24 @@ namespace Umbraco.Infrastructure.HostedServices
private readonly ILogger<LogScrubber> _logger;
private readonly IScopeProvider _scopeProvider;
public LogScrubber(IMainDom mainDom, IServerRegistrar serverRegistrar, IAuditService auditService, IOptions<LoggingSettings> settings, IScopeProvider scopeProvider, ILogger<LogScrubber> logger, IProfilingLogger profilingLogger)
/// <summary>
/// Initializes a new instance of the <see cref="LogScrubber"/> class.
/// </summary>
/// <param name="mainDom">Representation of the main application domain.</param>
/// <param name="serverRegistrar">Provider of server registrations to the distributed cache.</param>
/// <param name="auditService">Service for handling audit operations.</param>
/// <param name="settings">The configuration for logging settings.</param>
/// <param name="scopeProvider">Provides scopes for database operations.</param>
/// <param name="logger">The typed logger.</param>
/// <param name="profilingLogger">The profiling logger.</param>
public LogScrubber(
IMainDom mainDom,
IServerRegistrar serverRegistrar,
IAuditService auditService,
IOptions<LoggingSettings> settings,
IScopeProvider scopeProvider,
ILogger<LogScrubber> logger,
IProfilingLogger profilingLogger)
: base(TimeSpan.FromHours(4), DefaultDelay)
{
_mainDom = mainDom;
@@ -39,32 +59,34 @@ namespace Umbraco.Infrastructure.HostedServices
_profilingLogger = profilingLogger;
}
internal override async Task PerformExecuteAsync(object state)
internal override Task PerformExecuteAsync(object state)
{
switch (_serverRegistrar.GetCurrentServerRole())
{
case ServerRole.Replica:
_logger.LogDebug("Does not run on replica servers.");
return;
return Task.CompletedTask;
case ServerRole.Unknown:
_logger.LogDebug("Does not run on servers with unknown role.");
return;
return Task.CompletedTask;
}
// Ensure we do not run if not main domain, but do NOT lock it
if (_mainDom.IsMainDom == false)
{
_logger.LogDebug("Does not run if not MainDom.");
return;
return Task.CompletedTask;
}
// Ensure we use an explicit scope since we are running on a background thread.
using (var scope = _scopeProvider.CreateScope())
using (IScope scope = _scopeProvider.CreateScope())
using (_profilingLogger.DebugDuration<LogScrubber>("Log scrubbing executing", "Log scrubbing complete"))
{
_auditService.CleanLogs((int)_settings.MaxLogAge.TotalMinutes);
scope.Complete();
_ = scope.Complete();
}
return Task.CompletedTask;
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
@@ -13,44 +16,54 @@ namespace Umbraco.Infrastructure.HostedServices
/// </remarks>
public abstract class RecurringHostedServiceBase : IHostedService, IDisposable
{
/// <summary>
/// The default delay to use for recurring tasks for the first run after application start-up if no alternative is configured.
/// </summary>
protected static readonly TimeSpan DefaultDelay = TimeSpan.FromMinutes(3);
private readonly TimeSpan _period;
private readonly TimeSpan _delay;
private Timer _timer;
/// <summary>
/// Initializes a new instance of the <see cref="RecurringHostedServiceBase"/> class.
/// </summary>
/// <param name="period">Timepsan representing how often the task should recur.</param>
/// <param name="delay">Timespan represeting the initial delay after application start-up before the first run of the task occurs.</param>
protected RecurringHostedServiceBase(TimeSpan period, TimeSpan delay)
{
_period = period;
_delay = delay;
}
/// <inheritdoc/>
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(ExecuteAsync, null, (int)_delay.TotalMilliseconds, (int)_period.TotalMilliseconds);
return Task.CompletedTask;
}
public async void ExecuteAsync(object state)
{
/// <summary>
/// Executes the task.
/// </summary>
/// <param name="state">The task state.</param>
public async void ExecuteAsync(object state) =>
// Delegate work to method returning a task, that can be called and asserted in a unit test.
// Without this there can be behaviour where tests pass, but an error within them causes the test
// running process to crash.
// Hat-tip: https://stackoverflow.com/a/14207615/489433
await PerformExecuteAsync(state);
}
internal abstract Task PerformExecuteAsync(object state);
/// <inheritdoc/>
public Task StopAsync(CancellationToken cancellationToken)
{
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
/// <inheritdoc/>
public void Dispose() => _timer?.Dispose();
}
}

View File

@@ -1,8 +1,13 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Core.Sync;
using Umbraco.Web;
@@ -19,18 +24,35 @@ namespace Umbraco.Infrastructure.HostedServices
private readonly IContentService _contentService;
private readonly ILogger<ScheduledPublishing> _logger;
private readonly IMainDom _mainDom;
private readonly IRuntimeState _runtime;
private readonly IRuntimeState _runtimeState;
private readonly IServerMessenger _serverMessenger;
private readonly IBackOfficeSecurityFactory _backofficeSecurityFactory;
private readonly IServerRegistrar _serverRegistrar;
private readonly IUmbracoContextFactory _umbracoContextFactory;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledPublishing"/> class.
/// </summary>
/// <param name="runtimeState">Representation of the state of the Umbraco runtime.</param>
/// <param name="mainDom">Representation of the main application domain.</param>
/// <param name="serverRegistrar">Provider of server registrations to the distributed cache.</param>
/// <param name="contentService">Service for handling content operations.</param>
/// <param name="umbracoContextFactory">Service for creating and managing Umbraco context.</param>
/// <param name="logger">The typed logger.</param>
/// <param name="serverMessenger">Service broadcasting cache notifications to registered servers.</param>
/// <param name="backofficeSecurityFactory">Creates and manages <see cref="IBackOfficeSecurity"/> instances.</param>
public ScheduledPublishing(
IRuntimeState runtime, IMainDom mainDom, IServerRegistrar serverRegistrar, IContentService contentService,
IUmbracoContextFactory umbracoContextFactory, ILogger<ScheduledPublishing> logger, IServerMessenger serverMessenger, IBackOfficeSecurityFactory backofficeSecurityFactory)
IRuntimeState runtimeState,
IMainDom mainDom,
IServerRegistrar serverRegistrar,
IContentService contentService,
IUmbracoContextFactory umbracoContextFactory,
ILogger<ScheduledPublishing> logger,
IServerMessenger serverMessenger,
IBackOfficeSecurityFactory backofficeSecurityFactory)
: base(TimeSpan.FromMinutes(1), DefaultDelay)
{
_runtime = runtime;
_runtimeState = runtimeState;
_mainDom = mainDom;
_serverRegistrar = serverRegistrar;
_contentService = contentService;
@@ -40,35 +62,35 @@ namespace Umbraco.Infrastructure.HostedServices
_backofficeSecurityFactory = backofficeSecurityFactory;
}
internal override async Task PerformExecuteAsync(object state)
internal override Task PerformExecuteAsync(object state)
{
if (Suspendable.ScheduledPublishing.CanRun == false)
{
return;
return Task.CompletedTask;
}
switch (_serverRegistrar.GetCurrentServerRole())
{
case ServerRole.Replica:
_logger.LogDebug("Does not run on replica servers.");
return;
return Task.CompletedTask;
case ServerRole.Unknown:
_logger.LogDebug("Does not run on servers with unknown role.");
return;
return Task.CompletedTask;
}
// Ensure we do not run if not main domain, but do NOT lock it
if (_mainDom.IsMainDom == false)
{
_logger.LogDebug("Does not run if not MainDom.");
return;
return Task.CompletedTask;
}
// Do NOT run publishing if not properly running
if (_runtime.Level != RuntimeLevel.Run)
if (_runtimeState.Level != RuntimeLevel.Run)
{
_logger.LogDebug("Does not run if run level is not Run.");
return;
return Task.CompletedTask;
}
try
@@ -85,16 +107,17 @@ namespace Umbraco.Infrastructure.HostedServices
// - and we should definitively *not* have to flush it here (should be auto)
//
_backofficeSecurityFactory.EnsureBackOfficeSecurity();
using var contextReference = _umbracoContextFactory.EnsureUmbracoContext();
using UmbracoContextReference contextReference = _umbracoContextFactory.EnsureUmbracoContext();
try
{
// Run
var result = _contentService.PerformScheduledPublish(DateTime.Now);
foreach (var grouped in result.GroupBy(x => x.Result))
IEnumerable<PublishResult> result = _contentService.PerformScheduledPublish(DateTime.Now);
foreach (IGrouping<PublishResultType, PublishResult> grouped in result.GroupBy(x => x.Result))
{
_logger.LogInformation(
"Scheduled publishing result: '{StatusCount}' items with status {Status}",
grouped.Count(), grouped.Key);
grouped.Count(),
grouped.Key);
}
}
finally
@@ -112,7 +135,7 @@ namespace Umbraco.Infrastructure.HostedServices
_logger.LogError(ex, "Failed.");
}
return;
return Task.CompletedTask;
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -20,6 +23,10 @@ namespace Umbraco.Infrastructure.HostedServices.ServerRegistration
/// <summary>
/// Initializes a new instance of the <see cref="InstructionProcessTask"/> class.
/// </summary>
/// <param name="runtimeState">Representation of the state of the Umbraco runtime.</param>
/// <param name="messenger">Service broadcasting cache notifications to registered servers.</param>
/// <param name="logger">The typed logger.</param>
/// <param name="globalSettings">The configuration for global settings.</param>
public InstructionProcessTask(IRuntimeState runtimeState, IServerMessenger messenger, ILogger<InstructionProcessTask> logger, IOptions<GlobalSettings> globalSettings)
: base(globalSettings.Value.DatabaseServerMessenger.TimeBetweenSyncOperations, TimeSpan.FromMinutes(1))
{
@@ -28,11 +35,11 @@ namespace Umbraco.Infrastructure.HostedServices.ServerRegistration
_logger = logger;
}
internal override async Task PerformExecuteAsync(object state)
internal override Task PerformExecuteAsync(object state)
{
if (_runtimeState.Level != RuntimeLevel.Run)
{
return;
return Task.CompletedTask;
}
try
@@ -43,6 +50,8 @@ namespace Umbraco.Infrastructure.HostedServices.ServerRegistration
{
_logger.LogError(e, "Failed (will repeat).");
}
return Task.CompletedTask;
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -18,11 +21,16 @@ namespace Umbraco.Infrastructure.HostedServices.ServerRegistration
private readonly IServerRegistrationService _serverRegistrationService;
private readonly IRequestAccessor _requestAccessor;
private readonly ILogger<TouchServerTask> _logger;
private GlobalSettings _globalSettings;
private readonly GlobalSettings _globalSettings;
/// <summary>
/// Initializes a new instance of the <see cref="TouchServerTask"/> class.
/// </summary>
/// <param name="runtimeState">Representation of the state of the Umbraco runtime.</param>
/// <param name="serverRegistrationService">Services for server registrations.</param>
/// <param name="requestAccessor">Accessor for the current request.</param>
/// <param name="logger">The typed logger.</param>
/// <param name="globalSettings">The configuration for global settings.</param>
public TouchServerTask(IRuntimeState runtimeState, IServerRegistrationService serverRegistrationService, IRequestAccessor requestAccessor, ILogger<TouchServerTask> logger, IOptions<GlobalSettings> globalSettings)
: base(globalSettings.Value.DatabaseServerRegistrar.WaitTimeBetweenCalls, TimeSpan.FromSeconds(15))
{
@@ -33,18 +41,18 @@ namespace Umbraco.Infrastructure.HostedServices.ServerRegistration
_globalSettings = globalSettings.Value;
}
internal override async Task PerformExecuteAsync(object state)
internal override Task PerformExecuteAsync(object state)
{
if (_runtimeState.Level != RuntimeLevel.Run)
{
return;
return Task.CompletedTask;
}
var serverAddress = _requestAccessor.GetApplicationUrl()?.ToString();
if (serverAddress.IsNullOrWhiteSpace())
{
_logger.LogWarning("No umbracoApplicationUrl for service (yet), skip.");
return;
return Task.CompletedTask;
}
try
@@ -57,6 +65,8 @@ namespace Umbraco.Infrastructure.HostedServices.ServerRegistration
{
_logger.LogError(ex, "Failed to update server record in database.");
}
return Task.CompletedTask;
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
@@ -23,6 +26,12 @@ namespace Umbraco.Infrastructure.HostedServices
private readonly DirectoryInfo[] _tempFolders;
private readonly TimeSpan _age = TimeSpan.FromDays(1);
/// <summary>
/// Initializes a new instance of the <see cref="TempFileCleanup"/> class.
/// </summary>
/// <param name="ioHelper">Helper service for IO operations.</param>
/// <param name="mainDom">Representation of the main application domain.</param>
/// <param name="logger">The typed logger.</param>
public TempFileCleanup(IIOHelper ioHelper, IMainDom mainDom, ILogger<TempFileCleanup> logger)
: base(TimeSpan.FromMinutes(60), DefaultDelay)
{
@@ -33,33 +42,33 @@ namespace Umbraco.Infrastructure.HostedServices
_tempFolders = _ioHelper.GetTempFolders();
}
internal override async Task PerformExecuteAsync(object state)
internal override Task PerformExecuteAsync(object state)
{
// Ensure we do not run if not main domain
if (_mainDom.IsMainDom == false)
{
_logger.LogDebug("Does not run if not MainDom.");
return;
return Task.CompletedTask;
}
foreach (var folder in _tempFolders)
foreach (DirectoryInfo folder in _tempFolders)
{
CleanupFolder(folder);
}
return;
return Task.CompletedTask;
}
private void CleanupFolder(DirectoryInfo folder)
{
var result = _ioHelper.CleanFolder(folder, _age);
CleanFolderResult result = _ioHelper.CleanFolder(folder, _age);
switch (result.Status)
{
case CleanFolderResultStatus.FailedAsDoesNotExist:
_logger.LogDebug("The cleanup folder doesn't exist {Folder}", folder.FullName);
break;
case CleanFolderResultStatus.FailedWithException:
foreach (var error in result.Errors)
foreach (CleanFolderResult.Error error in result.Errors)
{
_logger.LogError(error.Exception, "Could not delete temp file {FileName}", error.ErroringFile.FullName);
}
@@ -74,8 +83,8 @@ namespace Umbraco.Infrastructure.HostedServices
return;
}
var files = folder.GetFiles("*.*", SearchOption.AllDirectories);
foreach (var file in files)
FileInfo[] files = folder.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
if (DateTime.UtcNow - file.LastWriteTimeUtc > _age)
{

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
@@ -25,14 +28,14 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
{
private Mock<IHealthCheckNotificationMethod> _mockNotificationMethod;
private const string _check1Id = "00000000-0000-0000-0000-000000000001";
private const string _check2Id = "00000000-0000-0000-0000-000000000002";
private const string _check3Id = "00000000-0000-0000-0000-000000000003";
private const string Check1Id = "00000000-0000-0000-0000-000000000001";
private const string Check2Id = "00000000-0000-0000-0000-000000000002";
private const string Check3Id = "00000000-0000-0000-0000-000000000003";
[Test]
public async Task Does_Not_Execute_When_Not_Enabled()
{
var sut = CreateHealthCheckNotifier(enabled: false);
HealthCheckNotifier sut = CreateHealthCheckNotifier(enabled: false);
await sut.PerformExecuteAsync(null);
VerifyNotificationsNotSent();
}
@@ -44,7 +47,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[TestCase(RuntimeLevel.BootFailed)]
public async Task Does_Not_Execute_When_Runtime_State_Is_Not_Run(RuntimeLevel runtimeLevel)
{
var sut = CreateHealthCheckNotifier(runtimeLevel: runtimeLevel);
HealthCheckNotifier sut = CreateHealthCheckNotifier(runtimeLevel: runtimeLevel);
await sut.PerformExecuteAsync(null);
VerifyNotificationsNotSent();
}
@@ -52,7 +55,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Server_Role_Is_Replica()
{
var sut = CreateHealthCheckNotifier(serverRole: ServerRole.Replica);
HealthCheckNotifier sut = CreateHealthCheckNotifier(serverRole: ServerRole.Replica);
await sut.PerformExecuteAsync(null);
VerifyNotificationsNotSent();
}
@@ -60,7 +63,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Server_Role_Is_Unknown()
{
var sut = CreateHealthCheckNotifier(serverRole: ServerRole.Unknown);
HealthCheckNotifier sut = CreateHealthCheckNotifier(serverRole: ServerRole.Unknown);
await sut.PerformExecuteAsync(null);
VerifyNotificationsNotSent();
}
@@ -68,7 +71,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Not_Main_Dom()
{
var sut = CreateHealthCheckNotifier(isMainDom: false);
HealthCheckNotifier sut = CreateHealthCheckNotifier(isMainDom: false);
await sut.PerformExecuteAsync(null);
VerifyNotificationsNotSent();
}
@@ -76,7 +79,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_With_No_Enabled_Notification_Methods()
{
var sut = CreateHealthCheckNotifier(notificationEnabled: false);
HealthCheckNotifier sut = CreateHealthCheckNotifier(notificationEnabled: false);
await sut.PerformExecuteAsync(null);
VerifyNotificationsNotSent();
}
@@ -84,7 +87,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Executes_With_Enabled_Notification_Methods()
{
var sut = CreateHealthCheckNotifier();
HealthCheckNotifier sut = CreateHealthCheckNotifier();
await sut.PerformExecuteAsync(null);
VerifyNotificationsSent();
}
@@ -92,10 +95,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Executes_Only_Enabled_Checks()
{
var sut = CreateHealthCheckNotifier();
HealthCheckNotifier sut = CreateHealthCheckNotifier();
await sut.PerformExecuteAsync(null);
_mockNotificationMethod.Verify(x => x.SendAsync(It.Is<HealthCheckResults>(
y => y.ResultsAsDictionary.Count == 1 && y.ResultsAsDictionary.ContainsKey("Check1"))), Times.Once);
_mockNotificationMethod.Verify(
x => x.SendAsync(
It.Is<HealthCheckResults>(y => y.ResultsAsDictionary.Count == 1 && y.ResultsAsDictionary.ContainsKey("Check1"))), Times.Once);
}
private HealthCheckNotifier CreateHealthCheckNotifier(
@@ -112,12 +116,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
Enabled = enabled,
DisabledChecks = new List<DisabledHealthCheckSettings>
{
new DisabledHealthCheckSettings { Id = Guid.Parse(_check3Id) }
new DisabledHealthCheckSettings { Id = Guid.Parse(Check3Id) }
}
},
DisabledChecks = new List<DisabledHealthCheckSettings>
{
new DisabledHealthCheckSettings { Id = Guid.Parse(_check2Id) }
new DisabledHealthCheckSettings { Id = Guid.Parse(Check2Id) }
}
};
var checks = new HealthCheckCollection(new List<HealthCheck>
@@ -144,52 +148,45 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
var mockLogger = new Mock<ILogger<HealthCheckNotifier>>();
var mockProfilingLogger = new Mock<IProfilingLogger>();
return new HealthCheckNotifier(Options.Create(settings), checks, notifications,
mockRunTimeState.Object, mockServerRegistrar.Object, mockMainDom.Object, mockScopeProvider.Object,
mockLogger.Object, mockProfilingLogger.Object, Mock.Of<ICronTabParser>());
return new HealthCheckNotifier(
Options.Create(settings),
checks,
notifications,
mockRunTimeState.Object,
mockServerRegistrar.Object,
mockMainDom.Object,
mockScopeProvider.Object,
mockLogger.Object,
mockProfilingLogger.Object,
Mock.Of<ICronTabParser>());
}
private void VerifyNotificationsNotSent()
{
VerifyNotificationsSentTimes(Times.Never());
}
private void VerifyNotificationsNotSent() => VerifyNotificationsSentTimes(Times.Never());
private void VerifyNotificationsSent()
{
VerifyNotificationsSentTimes(Times.Once());
}
private void VerifyNotificationsSent() => VerifyNotificationsSentTimes(Times.Once());
private void VerifyNotificationsSentTimes(Times times)
{
_mockNotificationMethod.Verify(x => x.SendAsync(It.IsAny<HealthCheckResults>()), times);
}
private void VerifyNotificationsSentTimes(Times times) => _mockNotificationMethod.Verify(x => x.SendAsync(It.IsAny<HealthCheckResults>()), times);
[HealthCheck(_check1Id, "Check1")]
[HealthCheck(Check1Id, "Check1")]
private class TestHealthCheck1 : TestHealthCheck
{
}
[HealthCheck(_check2Id, "Check2")]
[HealthCheck(Check2Id, "Check2")]
private class TestHealthCheck2 : TestHealthCheck
{
}
[HealthCheck(_check3Id, "Check3")]
[HealthCheck(Check3Id, "Check3")]
private class TestHealthCheck3 : TestHealthCheck
{
}
private class TestHealthCheck : HealthCheck
{
public override HealthCheckStatus ExecuteAction(HealthCheckAction action)
{
return new HealthCheckStatus("Check message");
}
public override HealthCheckStatus ExecuteAction(HealthCheckAction action) => new HealthCheckStatus("Check message");
public override IEnumerable<HealthCheckStatus> GetStatus()
{
return Enumerable.Empty<HealthCheckStatus>();
}
public override IEnumerable<HealthCheckStatus> GetStatus() => Enumerable.Empty<HealthCheckStatus>();
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
@@ -23,12 +26,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
{
private Mock<HttpMessageHandler> _mockHttpMessageHandler;
private const string _applicationUrl = "https://mysite.com";
private const string ApplicationUrl = "https://mysite.com";
[Test]
public async Task Does_Not_Execute_When_Not_Enabled()
{
var sut = CreateKeepAlive(enabled: false);
KeepAlive sut = CreateKeepAlive(enabled: false);
await sut.PerformExecuteAsync(null);
VerifyKeepAliveRequestNotSent();
}
@@ -36,7 +39,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Server_Role_Is_Replica()
{
var sut = CreateKeepAlive(serverRole: ServerRole.Replica);
KeepAlive sut = CreateKeepAlive(serverRole: ServerRole.Replica);
await sut.PerformExecuteAsync(null);
VerifyKeepAliveRequestNotSent();
}
@@ -44,7 +47,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Server_Role_Is_Unknown()
{
var sut = CreateKeepAlive(serverRole: ServerRole.Unknown);
KeepAlive sut = CreateKeepAlive(serverRole: ServerRole.Unknown);
await sut.PerformExecuteAsync(null);
VerifyKeepAliveRequestNotSent();
}
@@ -52,7 +55,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Not_Main_Dom()
{
var sut = CreateKeepAlive(isMainDom: false);
KeepAlive sut = CreateKeepAlive(isMainDom: false);
await sut.PerformExecuteAsync(null);
VerifyKeepAliveRequestNotSent();
}
@@ -60,7 +63,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Executes_And_Calls_Ping_Url()
{
var sut = CreateKeepAlive();
KeepAlive sut = CreateKeepAlive();
await sut.PerformExecuteAsync(null);
VerifyKeepAliveRequestSent();
}
@@ -76,7 +79,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
};
var mockRequestAccessor = new Mock<IRequestAccessor>();
mockRequestAccessor.Setup(x => x.GetApplicationUrl()).Returns(new Uri(_applicationUrl));
mockRequestAccessor.Setup(x => x.GetApplicationUrl()).Returns(new Uri(ApplicationUrl));
var mockServerRegistrar = new Mock<IServerRegistrar>();
mockServerRegistrar.Setup(x => x.GetCurrentServerRole()).Returns(serverRole);
@@ -99,26 +102,25 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
var mockHttpClientFactory = new Mock<IHttpClientFactory>(MockBehavior.Strict);
mockHttpClientFactory.Setup(x => x.CreateClient(It.IsAny<string>())).Returns(httpClient);
return new KeepAlive(mockRequestAccessor.Object, mockMainDom.Object, Options.Create(settings),
mockLogger.Object, mockProfilingLogger.Object, mockServerRegistrar.Object, mockHttpClientFactory.Object);
return new KeepAlive(
mockRequestAccessor.Object,
mockMainDom.Object,
Options.Create(settings),
mockLogger.Object,
mockProfilingLogger.Object,
mockServerRegistrar.Object,
mockHttpClientFactory.Object);
}
private void VerifyKeepAliveRequestNotSent()
{
VerifyKeepAliveRequestSentTimes(Times.Never());
}
private void VerifyKeepAliveRequestNotSent() => VerifyKeepAliveRequestSentTimes(Times.Never());
private void VerifyKeepAliveRequestSent()
{
VerifyKeepAliveRequestSentTimes(Times.Once());
}
private void VerifyKeepAliveRequestSent() => VerifyKeepAliveRequestSentTimes(Times.Once());
private void VerifyKeepAliveRequestSentTimes(Times times)
{
_mockHttpMessageHandler.Protected().Verify("SendAsync",
private void VerifyKeepAliveRequestSentTimes(Times times) => _mockHttpMessageHandler.Protected()
.Verify(
"SendAsync",
times,
ItExpr.Is<HttpRequestMessage>(x => x.RequestUri.ToString() == $"{_applicationUrl}/api/keepalive/ping"),
ItExpr.Is<HttpRequestMessage>(x => x.RequestUri.ToString() == $"{ApplicationUrl}/api/keepalive/ping"),
ItExpr.IsAny<CancellationToken>());
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Data;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
@@ -21,12 +24,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
{
private Mock<IAuditService> _mockAuditService;
const int _maxLogAgeInMinutes = 60;
private const int MaxLogAgeInMinutes = 60;
[Test]
public async Task Does_Not_Execute_When_Server_Role_Is_Replica()
{
var sut = CreateLogScrubber(serverRole: ServerRole.Replica);
LogScrubber sut = CreateLogScrubber(serverRole: ServerRole.Replica);
await sut.PerformExecuteAsync(null);
VerifyLogsNotScrubbed();
}
@@ -34,7 +37,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Server_Role_Is_Unknown()
{
var sut = CreateLogScrubber(serverRole: ServerRole.Unknown);
LogScrubber sut = CreateLogScrubber(serverRole: ServerRole.Unknown);
await sut.PerformExecuteAsync(null);
VerifyLogsNotScrubbed();
}
@@ -42,7 +45,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Not_Main_Dom()
{
var sut = CreateLogScrubber(isMainDom: false);
LogScrubber sut = CreateLogScrubber(isMainDom: false);
await sut.PerformExecuteAsync(null);
VerifyLogsNotScrubbed();
}
@@ -50,7 +53,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Executes_And_Scrubs_Logs()
{
var sut = CreateLogScrubber();
LogScrubber sut = CreateLogScrubber();
await sut.PerformExecuteAsync(null);
VerifyLogsScrubbed();
}
@@ -61,7 +64,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
{
var settings = new LoggingSettings
{
MaxLogAge = TimeSpan.FromMinutes(_maxLogAgeInMinutes),
MaxLogAge = TimeSpan.FromMinutes(MaxLogAgeInMinutes),
};
var mockServerRegistrar = new Mock<IServerRegistrar>();
@@ -80,23 +83,20 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
_mockAuditService = new Mock<IAuditService>();
return new LogScrubber(mockMainDom.Object, mockServerRegistrar.Object, _mockAuditService.Object,
Options.Create(settings), mockScopeProvider.Object, mockLogger.Object, mockProfilingLogger.Object);
return new LogScrubber(
mockMainDom.Object,
mockServerRegistrar.Object,
_mockAuditService.Object,
Options.Create(settings),
mockScopeProvider.Object,
mockLogger.Object,
mockProfilingLogger.Object);
}
private void VerifyLogsNotScrubbed()
{
VerifyLogsScrubbed(Times.Never());
}
private void VerifyLogsNotScrubbed() => VerifyLogsScrubbed(Times.Never());
private void VerifyLogsScrubbed()
{
VerifyLogsScrubbed(Times.Once());
}
private void VerifyLogsScrubbed() => VerifyLogsScrubbed(Times.Once());
private void VerifyLogsScrubbed(Times times)
{
_mockAuditService.Verify(x => x.CleanLogs(It.Is<int>(y => y == _maxLogAgeInMinutes)), times);
}
private void VerifyLogsScrubbed(Times times) => _mockAuditService.Verify(x => x.CleanLogs(It.Is<int>(y => y == MaxLogAgeInMinutes)), times);
}
}

View File

@@ -1,15 +1,16 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
using Umbraco.Core.Sync;
using Umbraco.Infrastructure.HostedServices;
using Umbraco.Web;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
{
@@ -22,7 +23,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Not_Enabled()
{
var sut = CreateScheduledPublishing(enabled: false);
ScheduledPublishing sut = CreateScheduledPublishing(enabled: false);
await sut.PerformExecuteAsync(null);
VerifyScheduledPublishingNotPerformed();
}
@@ -34,7 +35,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[TestCase(RuntimeLevel.BootFailed)]
public async Task Does_Not_Execute_When_Runtime_State_Is_Not_Run(RuntimeLevel runtimeLevel)
{
var sut = CreateScheduledPublishing(runtimeLevel: runtimeLevel);
ScheduledPublishing sut = CreateScheduledPublishing(runtimeLevel: runtimeLevel);
await sut.PerformExecuteAsync(null);
VerifyScheduledPublishingNotPerformed();
}
@@ -42,7 +43,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Server_Role_Is_Replica()
{
var sut = CreateScheduledPublishing(serverRole: ServerRole.Replica);
ScheduledPublishing sut = CreateScheduledPublishing(serverRole: ServerRole.Replica);
await sut.PerformExecuteAsync(null);
VerifyScheduledPublishingNotPerformed();
}
@@ -50,7 +51,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Server_Role_Is_Unknown()
{
var sut = CreateScheduledPublishing(serverRole: ServerRole.Unknown);
ScheduledPublishing sut = CreateScheduledPublishing(serverRole: ServerRole.Unknown);
await sut.PerformExecuteAsync(null);
VerifyScheduledPublishingNotPerformed();
}
@@ -58,7 +59,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Does_Not_Execute_When_Not_Main_Dom()
{
var sut = CreateScheduledPublishing(isMainDom: false);
ScheduledPublishing sut = CreateScheduledPublishing(isMainDom: false);
await sut.PerformExecuteAsync(null);
VerifyScheduledPublishingNotPerformed();
}
@@ -66,7 +67,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Executes_And_Performs_Scheduled_Publishing()
{
var sut = CreateScheduledPublishing();
ScheduledPublishing sut = CreateScheduledPublishing();
await sut.PerformExecuteAsync(null);
VerifyScheduledPublishingPerformed();
}
@@ -106,23 +107,21 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
var mockBackOfficeSecurityFactory = new Mock<IBackOfficeSecurityFactory>();
return new ScheduledPublishing(mockRunTimeState.Object, mockMainDom.Object, mockServerRegistrar.Object, _mockContentService.Object,
mockUmbracoContextFactory.Object, _mockLogger.Object, mockServerMessenger.Object, mockBackOfficeSecurityFactory.Object);
return new ScheduledPublishing(
mockRunTimeState.Object,
mockMainDom.Object,
mockServerRegistrar.Object,
_mockContentService.Object,
mockUmbracoContextFactory.Object,
_mockLogger.Object,
mockServerMessenger.Object,
mockBackOfficeSecurityFactory.Object);
}
private void VerifyScheduledPublishingNotPerformed()
{
VerifyScheduledPublishingPerformed(Times.Never());
}
private void VerifyScheduledPublishingNotPerformed() => VerifyScheduledPublishingPerformed(Times.Never());
private void VerifyScheduledPublishingPerformed()
{
VerifyScheduledPublishingPerformed(Times.Once());
}
private void VerifyScheduledPublishingPerformed() => VerifyScheduledPublishingPerformed(Times.Once());
private void VerifyScheduledPublishingPerformed(Times times)
{
_mockContentService.Verify(x => x.PerformScheduledPublish(It.IsAny<DateTime>()), times);
}
private void VerifyScheduledPublishingPerformed(Times times) => _mockContentService.Verify(x => x.PerformScheduledPublish(It.IsAny<DateTime>()), times);
}
}

View File

@@ -1,4 +1,7 @@
using System.Threading.Tasks;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
@@ -22,7 +25,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
[TestCase(RuntimeLevel.BootFailed)]
public async Task Does_Not_Execute_When_Runtime_State_Is_Not_Run(RuntimeLevel runtimeLevel)
{
var sut = CreateInstructionProcessTask(runtimeLevel: runtimeLevel);
InstructionProcessTask sut = CreateInstructionProcessTask(runtimeLevel: runtimeLevel);
await sut.PerformExecuteAsync(null);
VerifyMessengerNotSynced();
}
@@ -30,7 +33,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
[Test]
public async Task Executes_And_Touches_Server()
{
var sut = CreateInstructionProcessTask();
InstructionProcessTask sut = CreateInstructionProcessTask();
await sut.PerformExecuteAsync(null);
VerifyMessengerSynced();
}
@@ -49,19 +52,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
return new InstructionProcessTask(mockRunTimeState.Object, _mockDatabaseServerMessenger.Object, mockLogger.Object, Options.Create(settings));
}
private void VerifyMessengerNotSynced()
{
VerifyMessengerSyncedTimes(Times.Never());
}
private void VerifyMessengerNotSynced() => VerifyMessengerSyncedTimes(Times.Never());
private void VerifyMessengerSynced()
{
VerifyMessengerSyncedTimes(Times.Once());
}
private void VerifyMessengerSynced() => VerifyMessengerSyncedTimes(Times.Once());
private void VerifyMessengerSyncedTimes(Times times)
{
_mockDatabaseServerMessenger.Verify(x => x.Sync(), times);
}
private void VerifyMessengerSyncedTimes(Times times) => _mockDatabaseServerMessenger.Verify(x => x.Sync(), times);
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -17,8 +20,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
{
private Mock<IServerRegistrationService> _mockServerRegistrationService;
private const string _applicationUrl = "https://mysite.com/";
private const string _serverIdentity = "Test/1";
private const string ApplicationUrl = "https://mysite.com/";
private const string ServerIdentity = "Test/1";
private readonly TimeSpan _staleServerTimeout = TimeSpan.FromMinutes(2);
[TestCase(RuntimeLevel.Boot)]
@@ -28,7 +31,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
[TestCase(RuntimeLevel.BootFailed)]
public async Task Does_Not_Execute_When_Runtime_State_Is_Not_Run(RuntimeLevel runtimeLevel)
{
var sut = CreateTouchServerTask(runtimeLevel: runtimeLevel);
TouchServerTask sut = CreateTouchServerTask(runtimeLevel: runtimeLevel);
await sut.PerformExecuteAsync(null);
VerifyServerNotTouched();
}
@@ -36,7 +39,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
[Test]
public async Task Does_Not_Execute_When_Application_Url_Is_Not_Available()
{
var sut = CreateTouchServerTask(applicationUrl: string.Empty);
TouchServerTask sut = CreateTouchServerTask(applicationUrl: string.Empty);
await sut.PerformExecuteAsync(null);
VerifyServerNotTouched();
}
@@ -44,15 +47,15 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
[Test]
public async Task Executes_And_Touches_Server()
{
var sut = CreateTouchServerTask();
TouchServerTask sut = CreateTouchServerTask();
await sut.PerformExecuteAsync(null);
VerifyServerTouched();
}
private TouchServerTask CreateTouchServerTask(RuntimeLevel runtimeLevel = RuntimeLevel.Run, string applicationUrl = _applicationUrl)
private TouchServerTask CreateTouchServerTask(RuntimeLevel runtimeLevel = RuntimeLevel.Run, string applicationUrl = ApplicationUrl)
{
var mockRequestAccessor = new Mock<IRequestAccessor>();
mockRequestAccessor.Setup(x => x.GetApplicationUrl()).Returns(!string.IsNullOrEmpty(applicationUrl) ? new Uri(_applicationUrl) : null);
mockRequestAccessor.Setup(x => x.GetApplicationUrl()).Returns(!string.IsNullOrEmpty(applicationUrl) ? new Uri(ApplicationUrl) : null);
var mockRunTimeState = new Mock<IRuntimeState>();
mockRunTimeState.SetupGet(x => x.Level).Returns(runtimeLevel);
@@ -60,7 +63,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
var mockLogger = new Mock<ILogger<TouchServerTask>>();
_mockServerRegistrationService = new Mock<IServerRegistrationService>();
_mockServerRegistrationService.SetupGet(x => x.CurrentServerIdentity).Returns(_serverIdentity);
_mockServerRegistrationService.SetupGet(x => x.CurrentServerIdentity).Returns(ServerIdentity);
var settings = new GlobalSettings
{
@@ -70,28 +73,24 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices.ServerRe
}
};
return new TouchServerTask(mockRunTimeState.Object, _mockServerRegistrationService.Object, mockRequestAccessor.Object,
mockLogger.Object, Options.Create(settings));
return new TouchServerTask(
mockRunTimeState.Object,
_mockServerRegistrationService.Object,
mockRequestAccessor.Object,
mockLogger.Object,
Options.Create(settings));
}
private void VerifyServerNotTouched()
{
VerifyServerTouchedTimes(Times.Never());
}
private void VerifyServerNotTouched() => VerifyServerTouchedTimes(Times.Never());
private void VerifyServerTouched()
{
VerifyServerTouchedTimes(Times.Once());
}
private void VerifyServerTouched() => VerifyServerTouchedTimes(Times.Once());
private void VerifyServerTouchedTimes(Times times)
{
_mockServerRegistrationService
.Verify(x => x.TouchServer(
It.Is<string>(y => y == _applicationUrl),
It.Is<string>(y => y == _serverIdentity),
It.Is<TimeSpan>(y => y == _staleServerTimeout)),
times);
}
private void VerifyServerTouchedTimes(Times times) => _mockServerRegistrationService
.Verify(
x => x.TouchServer(
It.Is<string>(y => y == ApplicationUrl),
It.Is<string>(y => y == ServerIdentity),
It.Is<TimeSpan>(y => y == _staleServerTimeout)),
times);
}
}

View File

@@ -1,4 +1,7 @@
using System;
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
@@ -15,12 +18,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
public class TempFileCleanupTests
{
private Mock<IIOHelper> _mockIOHelper;
private string _testPath = Path.Combine(TestContext.CurrentContext.TestDirectory.Split("bin")[0], "App_Data", "TEMP");
private readonly string _testPath = Path.Combine(TestContext.CurrentContext.TestDirectory.Split("bin")[0], "App_Data", "TEMP");
[Test]
public async Task Does_Not_Execute_When_Not_Main_Dom()
{
var sut = CreateTempFileCleanup(isMainDom: false);
TempFileCleanup sut = CreateTempFileCleanup(isMainDom: false);
await sut.PerformExecuteAsync(null);
VerifyFilesNotCleaned();
}
@@ -28,7 +31,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
[Test]
public async Task Executes_And_Cleans_Files()
{
var sut = CreateTempFileCleanup();
TempFileCleanup sut = CreateTempFileCleanup();
await sut.PerformExecuteAsync(null);
VerifyFilesCleaned();
}
@@ -50,19 +53,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices
return new TempFileCleanup(_mockIOHelper.Object, mockMainDom.Object, mockLogger.Object);
}
private void VerifyFilesNotCleaned()
{
VerifyFilesCleaned(Times.Never());
}
private void VerifyFilesNotCleaned() => VerifyFilesCleaned(Times.Never());
private void VerifyFilesCleaned()
{
VerifyFilesCleaned(Times.Once());
}
private void VerifyFilesCleaned() => VerifyFilesCleaned(Times.Once());
private void VerifyFilesCleaned(Times times)
{
_mockIOHelper.Verify(x => x.CleanFolder(It.Is<DirectoryInfo>(y => y.FullName == _testPath), It.IsAny<TimeSpan>()), times);
}
private void VerifyFilesCleaned(Times times) => _mockIOHelper.Verify(x => x.CleanFolder(It.Is<DirectoryInfo>(y => y.FullName == _testPath), It.IsAny<TimeSpan>()), times);
}
}