Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System.Diagnostics;
using Xunit;

namespace NLog.Extensions.Hosting.Tests
{
public class HostAppNameLayoutRendererTests
{
[Fact]
public void RendersHostApplicationName()
{
// Arrange
var hostEnvironment = new TestHostEnvironment { ApplicationName = "TestApplication" };

// Act
var result = HostLayoutRendererTestHelper.Render<HostAppNameLayoutRenderer>("host-appname", "${host-appname}", hostEnvironment);

// Assert
Assert.Equal("TestApplication", result);
}

[Theory]
[InlineData("")]
[InlineData(" ")]
public void FallsBackToProcessNameWhenApplicationNameIsBlank(string applicationName)
{
// Arrange
var hostEnvironment = new TestHostEnvironment { ApplicationName = applicationName };
var processName = Process.GetCurrentProcess().ProcessName;

// Act
var result = HostLayoutRendererTestHelper.Render<HostAppNameLayoutRenderer>("host-appname", "${host-appname}", hostEnvironment);

// Assert
Assert.Equal(processName, result);
}

[Fact]
public void FallsBackToProcessNameWhenHostEnvironmentThrows()
{
// Arrange
var hostEnvironment = new TestHostEnvironment { ThrowOnApplicationName = true };
var processName = Process.GetCurrentProcess().ProcessName;

// Act
var result = HostLayoutRendererTestHelper.Render<HostAppNameLayoutRenderer>("host-appname", "${host-appname}", hostEnvironment);

// Assert
Assert.Equal(processName, result);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using Xunit;

namespace NLog.Extensions.Hosting.Tests
{
[Collection("Host renderer environment")]
public class HostEnvironmentLayoutRendererTests
{
[Fact]
public void RendersHostEnvironmentName()
{
// Arrange
var hostEnvironment = new TestHostEnvironment { EnvironmentName = "TestEnvironment" };

// Act
var result = HostLayoutRendererTestHelper.Render<HostEnvironmentLayoutRenderer>("host-environment", "${host-environment}", hostEnvironment);

// Assert
Assert.Equal("TestEnvironment", result);
}

[Fact]
public void UsesAspNetCoreEnvironmentBeforeDotnetEnvironmentAndTrimsIt()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_ENVIRONMENT", "DOTNET_ENVIRONMENT");
variables.Set("ASPNETCORE_ENVIRONMENT", " Staging ");
variables.Set("DOTNET_ENVIRONMENT", "Development");
var hostEnvironment = new TestHostEnvironment();

// Act
var result = HostLayoutRendererTestHelper.Render<HostEnvironmentLayoutRenderer>("host-environment", "${host-environment}", hostEnvironment);

// Assert
Assert.Equal("Staging", result);
}

[Fact]
public void UsesDotnetEnvironmentWhenAspNetCoreEnvironmentIsBlank()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_ENVIRONMENT", "DOTNET_ENVIRONMENT");
variables.Set("ASPNETCORE_ENVIRONMENT", " ");
variables.Set("DOTNET_ENVIRONMENT", " Development ");
var hostEnvironment = new TestHostEnvironment();

// Act
var result = HostLayoutRendererTestHelper.Render<HostEnvironmentLayoutRenderer>("host-environment", "${host-environment}", hostEnvironment);

// Assert
Assert.Equal("Development", result);
}

[Fact]
public void UsesEnvironmentFallbackWhenHostEnvironmentThrows()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_ENVIRONMENT", "DOTNET_ENVIRONMENT");
variables.Set("DOTNET_ENVIRONMENT", "TestEnvironment");
var hostEnvironment = new TestHostEnvironment { ThrowOnEnvironmentName = true };

// Act
var result = HostLayoutRendererTestHelper.Render<HostEnvironmentLayoutRenderer>("host-environment", "${host-environment}", hostEnvironment);

// Assert
Assert.Equal("TestEnvironment", result);
}

[Fact]
public void DefaultsToProductionWhenEnvironmentValuesAreMissing()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_ENVIRONMENT", "DOTNET_ENVIRONMENT");
var hostEnvironment = new TestHostEnvironment();

// Act
var result = HostLayoutRendererTestHelper.Render<HostEnvironmentLayoutRenderer>("host-environment", "${host-environment}", hostEnvironment);

// Assert
Assert.Equal("Production", result);
}

[Fact]
public void PreservesWhitespaceHostEnvironmentName()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_ENVIRONMENT", "DOTNET_ENVIRONMENT");
var hostEnvironment = new TestHostEnvironment { EnvironmentName = " " };

// Act
var result = HostLayoutRendererTestHelper.Render<HostEnvironmentLayoutRenderer>("host-environment", "${host-environment}", hostEnvironment);

// Assert
Assert.Equal(" ", result);
}
}
}
92 changes: 92 additions & 0 deletions test/NLog.Extensions.Hosting.Tests/HostLayoutRendererTestHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#nullable enable

using System;
using System.Collections.Generic;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using NLog.LayoutRenderers;
using Xunit;

namespace NLog.Extensions.Hosting.Tests
{
[CollectionDefinition("Host renderer environment", DisableParallelization = true)]
public class HostRendererEnvironmentCollection
{
}

internal static class HostLayoutRendererTestHelper
{
public static string Render<TLayoutRenderer>(string rendererName, string layout, IHostEnvironment? hostEnvironment = null)
where TLayoutRenderer : LayoutRenderer, new()
{
using var logFactory = new LogFactory();
var target = new Targets.MemoryTarget { Layout = layout };

logFactory.Setup().SetupExtensions(extensions =>
{
extensions.RegisterLayoutRenderer<TLayoutRenderer>(rendererName);
if (hostEnvironment is not null)
extensions.RegisterSingletonService(hostEnvironment);
});
logFactory.Setup().LoadConfiguration(configuration => configuration.ForLogger().WriteTo(target));

return target.Layout.Render(LogEventInfo.CreateNullEvent());
}
}

internal sealed class TestHostEnvironment : IHostEnvironment
{
private string _applicationName = string.Empty;
private string _contentRootPath = string.Empty;
private string _environmentName = string.Empty;

public bool ThrowOnApplicationName { get; set; }
public bool ThrowOnContentRootPath { get; set; }
public bool ThrowOnEnvironmentName { get; set; }

public string ApplicationName
{
get => ThrowOnApplicationName ? throw new InvalidOperationException() : _applicationName;
set => _applicationName = value;
}

public string ContentRootPath
{
get => ThrowOnContentRootPath ? throw new InvalidOperationException() : _contentRootPath;
set => _contentRootPath = value;
}

public string EnvironmentName
{
get => ThrowOnEnvironmentName ? throw new InvalidOperationException() : _environmentName;
set => _environmentName = value;
}

public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider();
}

internal sealed class EnvironmentVariableScope : IDisposable
{
private readonly Dictionary<string, string?> _originalValues = new Dictionary<string, string?>();

public EnvironmentVariableScope(params string[] variableNames)
{
foreach (var variableName in variableNames)
{
_originalValues[variableName] = Environment.GetEnvironmentVariable(variableName);
Environment.SetEnvironmentVariable(variableName, null);
}
}

public void Set(string variableName, string? value)
{
Environment.SetEnvironmentVariable(variableName, value);
}

public void Dispose()
{
foreach (var variable in _originalValues)
Environment.SetEnvironmentVariable(variable.Key, variable.Value);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System.IO;
using Xunit;

namespace NLog.Extensions.Hosting.Tests
{
[Collection("Host renderer environment")]
public class HostRootDirLayoutRendererTests
{
[Fact]
public void RendersHostContentRootWithoutTrailingSeparators()
{
// Arrange
var contentRootPath = Path.Combine(Path.GetTempPath(), "HostRoot") + Path.DirectorySeparatorChar + Path.AltDirectorySeparatorChar;
var hostEnvironment = new TestHostEnvironment { ContentRootPath = contentRootPath };

// Act
var result = HostLayoutRendererTestHelper.Render<HostRootDirLayoutRenderer>("host-rootdir", "${host-rootdir}", hostEnvironment);

// Assert
Assert.Equal(contentRootPath.TrimEnd(Path.DirectorySeparatorChar).TrimEnd(Path.AltDirectorySeparatorChar), result);
}

[Fact]
public void UsesAspNetCoreContentRootBeforeDotnetContentRoot()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_CONTENTROOT", "DOTNET_CONTENTROOT");
var aspNetCoreRoot = Path.Combine(Path.GetTempPath(), "AspNetCoreRoot") + Path.DirectorySeparatorChar;
variables.Set("ASPNETCORE_CONTENTROOT", $" {aspNetCoreRoot} ");
variables.Set("DOTNET_CONTENTROOT", Path.Combine(Path.GetTempPath(), "DotnetRoot"));
var hostEnvironment = new TestHostEnvironment();

// Act
var result = HostLayoutRendererTestHelper.Render<HostRootDirLayoutRenderer>("host-rootdir", "${host-rootdir}", hostEnvironment);

// Assert
Assert.Equal(aspNetCoreRoot.TrimEnd(Path.DirectorySeparatorChar).TrimEnd(Path.AltDirectorySeparatorChar), result);
}

[Fact]
public void UsesDotnetContentRootWhenAspNetCoreContentRootIsBlank()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_CONTENTROOT", "DOTNET_CONTENTROOT");
var dotnetRoot = Path.Combine(Path.GetTempPath(), "DotnetRoot") + Path.AltDirectorySeparatorChar;
variables.Set("ASPNETCORE_CONTENTROOT", " ");
variables.Set("DOTNET_CONTENTROOT", dotnetRoot);
var hostEnvironment = new TestHostEnvironment();

// Act
var result = HostLayoutRendererTestHelper.Render<HostRootDirLayoutRenderer>("host-rootdir", "${host-rootdir}", hostEnvironment);

// Assert
Assert.Equal(dotnetRoot.TrimEnd(Path.DirectorySeparatorChar).TrimEnd(Path.AltDirectorySeparatorChar), result);
}

[Fact]
public void UsesEnvironmentFallbackWhenHostContentRootThrows()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_CONTENTROOT", "DOTNET_CONTENTROOT");
var environmentRoot = Path.Combine(Path.GetTempPath(), "EnvironmentRoot");
variables.Set("DOTNET_CONTENTROOT", environmentRoot);
var hostEnvironment = new TestHostEnvironment { ThrowOnContentRootPath = true };

// Act
var result = HostLayoutRendererTestHelper.Render<HostRootDirLayoutRenderer>("host-rootdir", "${host-rootdir}", hostEnvironment);

// Assert
Assert.Equal(environmentRoot, result);
}

[Fact]
public void FallsBackToCurrentApplicationDirectoryWhenContentRootsAreMissing()
{
// Arrange
using var variables = new EnvironmentVariableScope("ASPNETCORE_CONTENTROOT", "DOTNET_CONTENTROOT");

// Act
var result = HostLayoutRendererTestHelper.Render<HostRootDirLayoutRenderer>("host-rootdir", "${host-rootdir}");

// Assert
Assert.True(Path.IsPathRooted(result));
Assert.NotEmpty(result);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Linq;
using NLog.Layouts;
using NLog.Extensions.Hosting;
using NLog.Extensions.Logging;
using Xunit;

namespace NLog.Extensions.Hosting.Tests
{
public class SetupExtensionsBuilderExtensionsTests
{
[Fact]
public void WriteToJsonTargets_ConfiguresJsonLayoutsAndScopes()
{
// Arrange
var logFactory = new LogFactory();

// Act
logFactory.Setup().LoadConfiguration(configuration =>
{
configuration.ForLogger().WriteToJsonFile(new SimpleLayout("test.json"), includeScopes: true);
configuration.ForLogger().WriteToJsonConsole();
});

// Assert
var fileTarget = Assert.IsType<Targets.FileTarget>(logFactory.Configuration.AllTargets.Single(target => target is Targets.FileTarget));
var consoleTarget = Assert.IsType<Targets.ConsoleTarget>(logFactory.Configuration.AllTargets.Single(target => target is Targets.ConsoleTarget));
Assert.True(Assert.IsType<MicrosoftConsoleJsonLayout>(fileTarget.Layout).IncludeScopes);
Assert.False(Assert.IsType<MicrosoftConsoleJsonLayout>(consoleTarget.Layout).IncludeScopes);
}
}
}
Loading