Skip to content

Convert xUnit assertions to Fluent Assertions style and optimize assertions #1542

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 14, 2025
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
Expand Up @@ -339,9 +339,9 @@ private static void AssertServiceDiscoveryClientsAreAutowired(HostWrapper hostWr
IDiscoveryClient[] discoveryClients = [.. hostWrapper.Services.GetServices<IDiscoveryClient>()];

discoveryClients.Should().HaveCount(3);
discoveryClients.Should().ContainSingle(discoveryClient => discoveryClient is ConfigurationDiscoveryClient);
discoveryClients.Should().ContainSingle(discoveryClient => discoveryClient is ConsulDiscoveryClient);
discoveryClients.Should().ContainSingle(discoveryClient => discoveryClient is EurekaDiscoveryClient);
discoveryClients.OfType<ConfigurationDiscoveryClient>().Should().ContainSingle();
discoveryClients.OfType<ConsulDiscoveryClient>().Should().ContainSingle();
discoveryClients.OfType<EurekaDiscoveryClient>().Should().ContainSingle();
}

private static void AssertPrometheusIsAutowired(HostWrapper hostWrapper)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public static string AsDotNetConfigurationKey(string key)
return sb.ToString(0, sb.Length - 1);
}

private static IEnumerable<string> UniversalHierarchySplit(string source)
private static List<string> UniversalHierarchySplit(string source)
{
List<string> result = [];

Expand Down Expand Up @@ -71,7 +71,7 @@ private static IEnumerable<string> UniversalHierarchySplit(string source)
}
}

return [.. result];
return result;

static string UnEscapeString(string src)
{
Expand Down
7 changes: 5 additions & 2 deletions src/Common/src/Logging/BootstrapLoggerFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ public sealed class BootstrapLoggerFactory : ILoggerFactory
loggingBuilder.AddConsole(options => options.MaxQueueLength = 1);
#pragma warning restore S4792 // Configuring loggers is security-sensitive

loggingBuilder.AddConfiguration(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
var appSettings = new Dictionary<string, string?>
{
["LogLevel:Default"] = "Information"
}).Build());
};

IConfigurationRoot configuration = new ConfigurationBuilder().AddInMemoryCollection(appSettings).Build();
loggingBuilder.AddConfiguration(configuration);
};

private readonly object _lock = new();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public void ConfigureCertificateOptions_ThrowsOnEmptyFile(string certificateName
var options = new CertificateOptions();

Action configureAction = () => configureOptions.Configure(certificateName, options);
configureAction.Should().Throw<CryptographicException>();
configureAction.Should().ThrowExactly<CryptographicException>();

options.Certificate.Should().BeNull();
}
Expand All @@ -88,7 +88,7 @@ public void ConfigureCertificateOptions_ThrowsOnInvalidKey(string certificateNam
var options = new CertificateOptions();

Action configureAction = () => configureOptions.Configure(certificateName, options);
configureAction.Should().Throw<CryptographicException>();
configureAction.Should().ThrowExactly<CryptographicException>();

options.Certificate.Should().BeNull();
}
Expand Down
4 changes: 2 additions & 2 deletions src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public void ConstructorSetsDefaults()
{
var options = new ApplicationInstanceInfo();

Assert.Null(options.ApplicationName);
options.ApplicationName.Should().BeNull();
}

[Fact]
Expand Down Expand Up @@ -50,7 +50,7 @@ public async Task ReadsApplicationConfiguration()

var options = serviceProvider.GetRequiredService<IApplicationInstanceInfo>();

Assert.Equal("my-app", options.ApplicationName);
options.ApplicationName.Should().Be("my-app");
}

[Fact]
Expand Down
6 changes: 3 additions & 3 deletions src/Common/test/Common.Test/Extensions/UriExtensionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public void MaskSingleBasicAuthentication()

string masked = uri.ToMaskedString();

Assert.Equal(expected, masked);
masked.Should().Be(expected);
}

[Fact]
Expand All @@ -27,7 +27,7 @@ public void MaskMultiBasicAuthentication()

string masked = uri.ToMaskedString();

Assert.Equal(expected, masked);
masked.Should().Be(expected);
}

[Fact]
Expand All @@ -38,6 +38,6 @@ public void DoNotMaskIfNoBasicAuthentication()

string masked = uri.ToMaskedString();

Assert.Equal(expected, masked);
masked.Should().Be(expected);
}
}
44 changes: 22 additions & 22 deletions src/Common/test/Common.Test/Net/InetUtilsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void TestGetFirstNonLoopbackHostInfo()
var optionsMonitor = new TestOptionsMonitor<InetOptions>();
var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.NotNull(inetUtils.FindFirstNonLoopbackHostInfo());
inetUtils.FindFirstNonLoopbackHostInfo().Should().NotBeNull();
}

[Fact]
Expand All @@ -30,7 +30,7 @@ public void TestGetFirstNonLoopbackAddress()

var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.NotNull(inetUtils.FindFirstNonLoopbackAddress());
inetUtils.FindFirstNonLoopbackAddress().Should().NotBeNull();
}

[Fact]
Expand All @@ -39,7 +39,7 @@ public void TestConvert()
var optionsMonitor = new TestOptionsMonitor<InetOptions>();
var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.NotNull(inetUtils.ConvertAddress(Dns.GetHostEntry("localhost").AddressList[0], optionsMonitor.CurrentValue));
inetUtils.ConvertAddress(Dns.GetHostEntry("localhost").AddressList[0], optionsMonitor.CurrentValue).Should().NotBeNull();
}

[Fact]
Expand All @@ -49,7 +49,7 @@ public void TestHostInfo()
var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);
HostInfo info = inetUtils.FindFirstNonLoopbackHostInfo();

Assert.NotNull(info.IPAddress);
info.IPAddress.Should().NotBeNull();
}

[Fact]
Expand All @@ -62,9 +62,9 @@ public void TestIgnoreInterface()

var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.True(inetUtils.IgnoreInterface("docker0", optionsMonitor.CurrentValue));
Assert.True(inetUtils.IgnoreInterface("vethAQI2QT", optionsMonitor.CurrentValue));
Assert.False(inetUtils.IgnoreInterface("docker1", optionsMonitor.CurrentValue));
inetUtils.IgnoreInterface("docker0", optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IgnoreInterface("vethAQI2QT", optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IgnoreInterface("docker1", optionsMonitor.CurrentValue).Should().BeFalse();
}

[Fact]
Expand All @@ -73,7 +73,7 @@ public void TestDefaultIgnoreInterface()
var optionsMonitor = new TestOptionsMonitor<InetOptions>();
var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.False(inetUtils.IgnoreInterface("docker0", optionsMonitor.CurrentValue));
inetUtils.IgnoreInterface("docker0", optionsMonitor.CurrentValue).Should().BeFalse();
}

[Fact]
Expand All @@ -86,8 +86,8 @@ public void TestSiteLocalAddresses()

var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("192.168.0.1"), optionsMonitor.CurrentValue));
Assert.False(inetUtils.IsPreferredAddress(IPAddress.Parse("5.5.8.1"), optionsMonitor.CurrentValue));
inetUtils.IsPreferredAddress(IPAddress.Parse("192.168.0.1"), optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IsPreferredAddress(IPAddress.Parse("5.5.8.1"), optionsMonitor.CurrentValue).Should().BeFalse();
}

[Fact]
Expand All @@ -100,10 +100,10 @@ public void TestPreferredNetworksRegex()

var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("192.168.0.1"), optionsMonitor.CurrentValue));
Assert.False(inetUtils.IsPreferredAddress(IPAddress.Parse("5.5.8.1"), optionsMonitor.CurrentValue));
Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("10.0.10.1"), optionsMonitor.CurrentValue));
Assert.False(inetUtils.IsPreferredAddress(IPAddress.Parse("10.255.10.1"), optionsMonitor.CurrentValue));
inetUtils.IsPreferredAddress(IPAddress.Parse("192.168.0.1"), optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IsPreferredAddress(IPAddress.Parse("5.5.8.1"), optionsMonitor.CurrentValue).Should().BeFalse();
inetUtils.IsPreferredAddress(IPAddress.Parse("10.0.10.1"), optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IsPreferredAddress(IPAddress.Parse("10.255.10.1"), optionsMonitor.CurrentValue).Should().BeFalse();
}

[Fact]
Expand All @@ -116,10 +116,10 @@ public void TestPreferredNetworksSimple()

var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("192.168.0.1"), optionsMonitor.CurrentValue));
Assert.False(inetUtils.IsPreferredAddress(IPAddress.Parse("5.5.8.1"), optionsMonitor.CurrentValue));
Assert.False(inetUtils.IsPreferredAddress(IPAddress.Parse("10.255.10.1"), optionsMonitor.CurrentValue));
Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("10.0.10.1"), optionsMonitor.CurrentValue));
inetUtils.IsPreferredAddress(IPAddress.Parse("192.168.0.1"), optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IsPreferredAddress(IPAddress.Parse("5.5.8.1"), optionsMonitor.CurrentValue).Should().BeFalse();
inetUtils.IsPreferredAddress(IPAddress.Parse("10.255.10.1"), optionsMonitor.CurrentValue).Should().BeFalse();
inetUtils.IsPreferredAddress(IPAddress.Parse("10.0.10.1"), optionsMonitor.CurrentValue).Should().BeTrue();
}

[Fact]
Expand All @@ -128,9 +128,9 @@ public void TestPreferredNetworksListIsEmpty()
var optionsMonitor = new TestOptionsMonitor<InetOptions>();
var inetUtils = new InetUtils(DomainNameResolver.Instance, optionsMonitor, NullLogger<InetUtils>.Instance);

Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("192.168.0.1"), optionsMonitor.CurrentValue));
Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("5.5.8.1"), optionsMonitor.CurrentValue));
Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("10.255.10.1"), optionsMonitor.CurrentValue));
Assert.True(inetUtils.IsPreferredAddress(IPAddress.Parse("10.0.10.1"), optionsMonitor.CurrentValue));
inetUtils.IsPreferredAddress(IPAddress.Parse("192.168.0.1"), optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IsPreferredAddress(IPAddress.Parse("5.5.8.1"), optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IsPreferredAddress(IPAddress.Parse("10.255.10.1"), optionsMonitor.CurrentValue).Should().BeTrue();
inetUtils.IsPreferredAddress(IPAddress.Parse("10.0.10.1"), optionsMonitor.CurrentValue).Should().BeTrue();
}
}
18 changes: 9 additions & 9 deletions src/Common/test/Common.Test/PlatformTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,39 @@ public sealed class PlatformTest
[Fact]
public void IsCloudFoundry_ReturnsExpected()
{
Assert.False(Platform.IsCloudFoundry);
Platform.IsCloudFoundry.Should().BeFalse();

using (new EnvironmentVariableScope("VCAP_APPLICATION", "{}"))
{
Assert.True(Platform.IsCloudFoundry);
Platform.IsCloudFoundry.Should().BeTrue();
}

Assert.False(Platform.IsCloudFoundry);
Platform.IsCloudFoundry.Should().BeFalse();
}

[Fact]
public void IsKubernetes_ReturnsExpected()
{
Assert.False(Platform.IsKubernetes);
Platform.IsKubernetes.Should().BeFalse();

using (new EnvironmentVariableScope("KUBERNETES_SERVICE_HOST", "some"))
{
Assert.True(Platform.IsKubernetes);
Platform.IsKubernetes.Should().BeTrue();
}

Assert.False(Platform.IsKubernetes);
Platform.IsKubernetes.Should().BeFalse();
}

[Fact]
public void IsContainerized_ReturnsExpected()
{
Assert.False(Platform.IsContainerized);
Platform.IsContainerized.Should().BeFalse();

using (new EnvironmentVariableScope("DOTNET_RUNNING_IN_CONTAINER", "true"))
{
Assert.True(Platform.IsContainerized);
Platform.IsContainerized.Should().BeTrue();
}

Assert.False(Platform.IsContainerized);
Platform.IsContainerized.Should().BeFalse();
}
}
10 changes: 5 additions & 5 deletions src/Common/test/Common.Test/SecurityUtilitiesTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@ public sealed class SecurityUtilitiesTest
[Fact]
public void SanitizeInput_ReturnsNullAndEmptyUnchanged()
{
Assert.Null(SecurityUtilities.SanitizeInput(null));
Assert.Equal(string.Empty, SecurityUtilities.SanitizeInput(string.Empty));
SecurityUtilities.SanitizeInput(null).Should().BeNull();
SecurityUtilities.SanitizeInput(string.Empty).Should().BeEmpty();
}

[Fact]
public void SanitizeInput_EncodesHtml()
{
Assert.Equal("&gt;some string&lt;", SecurityUtilities.SanitizeInput(">some string<"));
SecurityUtilities.SanitizeInput(">some string<").Should().Be("&gt;some string&lt;");
}

[Fact]
public void SanitizeInput_RemovesCrlf()
{
Assert.DoesNotContain("\r", SecurityUtilities.SanitizeInput("some\rparagraph\rwith\rcarriage\rreturns"), StringComparison.Ordinal);
Assert.DoesNotContain("\n", SecurityUtilities.SanitizeInput("some\nparagraph\nwith\nline\nendings"), StringComparison.Ordinal);
SecurityUtilities.SanitizeInput("some\rparagraph\rwith\rcarriage\rreturns").Should().NotContain("\r");
SecurityUtilities.SanitizeInput("some\nparagraph\nwith\nline\nendings").Should().NotContain("\n");
}
}
9 changes: 3 additions & 6 deletions src/Common/test/Http.Test/HttpClientExtensionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ public void ConfigureForSteeltoe_sets_user_agent_and_timeout()

httpClient.ConfigureForSteeltoe(5.Seconds());

httpClient.DefaultRequestHeaders.UserAgent.Should().ContainSingle();
httpClient.DefaultRequestHeaders.UserAgent.ElementAt(0).ToString().Should().Be(HttpClientExtensions.SteeltoeUserAgent);
httpClient.DefaultRequestHeaders.UserAgent.Should().ContainSingle().Which.ToString().Should().Be(HttpClientExtensions.SteeltoeUserAgent);

httpClient.Timeout.Should().Be(5.Seconds());
}
Expand All @@ -38,8 +37,7 @@ public async Task GetAccessTokenAsync_with_username_and_password_sends_request_w

handler.Mock.VerifyNoOutstandingExpectation();

httpClient.DefaultRequestHeaders.UserAgent.Should().ContainSingle();
httpClient.DefaultRequestHeaders.UserAgent.ElementAt(0).ToString().Should().Be(HttpClientExtensions.SteeltoeUserAgent);
httpClient.DefaultRequestHeaders.UserAgent.Should().ContainSingle().Which.ToString().Should().Be(HttpClientExtensions.SteeltoeUserAgent);

accessToken.Should().Be("secret");
}
Expand All @@ -59,8 +57,7 @@ public async Task GetAccessTokenAsync_with_only_password_sends_request_with_basi

handler.Mock.VerifyNoOutstandingExpectation();

httpClient.DefaultRequestHeaders.UserAgent.Should().ContainSingle();
httpClient.DefaultRequestHeaders.UserAgent.ElementAt(0).ToString().Should().Be(HttpClientExtensions.SteeltoeUserAgent);
httpClient.DefaultRequestHeaders.UserAgent.Should().ContainSingle().Which.ToString().Should().Be(HttpClientExtensions.SteeltoeUserAgent);

accessToken.Should().Be("secret");
}
Expand Down
11 changes: 6 additions & 5 deletions src/Common/test/Logging.Test/BootstrapperLoggerFactoryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,13 @@ public void Creates_default_minimum_levels()
[Fact]
public void Can_override_minimum_level()
{
var bootstrapLoggerFactory = BootstrapLoggerFactory.CreateConsole(loggingBuilder => loggingBuilder.AddConfiguration(new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["LogLevel:TestLogger"] = "Warning"
}).Build()));
var appSettings = new Dictionary<string, string?>
{
["LogLevel:TestLogger"] = "Warning"
};

IConfigurationRoot configuration = new ConfigurationBuilder().AddInMemoryCollection(appSettings).Build();
var bootstrapLoggerFactory = BootstrapLoggerFactory.CreateConsole(loggingBuilder => loggingBuilder.AddConfiguration(configuration));
ILogger logger = bootstrapLoggerFactory.CreateLogger("TestLogger");

logger.IsEnabled(LogLevel.Trace).Should().BeFalse();
Expand Down
2 changes: 1 addition & 1 deletion src/Common/test/TestResources/MemoryFileProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void IncludeFile(string path, byte[] contents)
ArgumentException.ThrowIfNullOrEmpty(path);
ArgumentNullException.ThrowIfNull(contents);

string[] pathSegments = [.. PathToSegments(path)];
string[] pathSegments = PathToSegments(path);
string[] parentDirectories = pathSegments[..^1];
string fileName = pathSegments[^1];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,14 @@ private IDiscoveryClient[] SetupDiscoveryClients(ILoggerFactory loggerFactory)
tempServices.AddSingleton(typeof(ILogger<>), typeof(Logger<>));

// force settings to make sure we don't register the app here
IConfiguration tempConfiguration = new ConfigurationBuilder().AddConfiguration(_configuration).AddInMemoryCollection(new Dictionary<string, string?>
var appSettings = new Dictionary<string, string?>
{
["Eureka:Client:ShouldRegisterWithEureka"] = "false",
["Eureka:Client:ShouldFetchRegistry"] = "true",
["Consul:Discovery:Register"] = "false"
}).Build();
};

IConfiguration tempConfiguration = new ConfigurationBuilder().AddConfiguration(_configuration).AddInMemoryCollection(appSettings).Build();
tempServices.AddSingleton(tempConfiguration);

if (AssemblyLoader.IsAssemblyLoaded("Steeltoe.Discovery.Configuration"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ public void WithVcapApplicationConfiguration()
options.ApplicationId.Should().Be("fa05c1a9-0fc1-4fbd-bae1-139850dec7a3");
options.ApplicationName.Should().Be("my-app");
options.Uris.Should().HaveCount(2);
options.Uris[0].Should().Be("my-app.10.244.0.34.xip.io");
options.Uris[1].Should().Be("my-app2.10.244.0.34.xip.io");
options.Uris.Should().HaveElementAt(0, "my-app.10.244.0.34.xip.io");
options.Uris.Should().HaveElementAt(1, "my-app2.10.244.0.34.xip.io");
options.ApplicationVersion.Should().Be("fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca");
options.Api.Should().Be("https://api.system.test-cloud.com");
options.Limits.Should().NotBeNull();
Expand Down
Loading
Loading