refactor: use `FluentAssertions.Analyzers` for Common tests (#694)

This commit is contained in:
Justin Perez 2023-08-03 11:21:15 -07:00 коммит произвёл GitHub
Родитель c2924b2413
Коммит eb783bd574
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
8 изменённых файлов: 70 добавлений и 62 удалений

Просмотреть файл

@ -6,6 +6,7 @@ using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using FluentAssertions;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@ -34,15 +35,15 @@ public class BaseDetectionTelemetryRecordTests
foreach (var type in this.recordTypes)
{
var inst = Activator.CreateInstance(type) as IDetectionTelemetryRecord;
Assert.IsNotNull(inst);
inst.Should().NotBeNull();
var recordName = inst.RecordName;
Assert.IsTrue(!string.IsNullOrEmpty(recordName), $"RecordName not set for {type.FullName}!");
recordName.Should().NotBeNullOrEmpty($"RecordName not set for {type.FullName}!");
if (dic.ContainsKey(recordName))
if (dic.TryGetValue(recordName, out var value))
{
Assert.Fail($"Duplicate RecordName:`{recordName}` found for {type.FullName} and {dic[recordName].FullName}!");
Assert.Fail($"Duplicate RecordName:`{recordName}` found for {type.FullName} and {value.FullName}!");
}
else
{

Просмотреть файл

@ -24,37 +24,40 @@ public class CommandLineInvocationServiceTests
[SkipTestIfNotWindows]
public async Task ShowsCmdExeAsExecutableAsync()
{
Assert.IsTrue(await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C"));
var result = await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C");
result.Should().BeTrue();
}
[SkipTestIfNotWindows]
public async Task FallbackWorksIfBadCommandsAreFirstAsync()
{
Assert.IsTrue(await this.commandLineService.CanCommandBeLocatedAsync("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe", "cmd.exe" }, "/C"));
var result = await this.commandLineService.CanCommandBeLocatedAsync("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe", "cmd.exe" }, "/C");
result.Should().BeTrue();
}
[SkipTestIfNotWindows]
public async Task ReturnsFalseIfNoValidCommandIsFoundAsync()
{
Assert.IsFalse(await this.commandLineService.CanCommandBeLocatedAsync("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe" }, "/C"));
var result = await this.commandLineService.CanCommandBeLocatedAsync("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe" }, "/C");
result.Should().BeFalse();
}
[SkipTestIfNotWindows]
public async Task ReturnsStandardOutputAsync()
{
var isLocated = await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C");
Assert.IsTrue(isLocated);
isLocated.Should().BeTrue();
var taskResult = await this.commandLineService.ExecuteCommandAsync("cmd.exe", default, "/C echo Expected Output");
Assert.AreEqual(0, taskResult.ExitCode);
Assert.AreEqual(string.Empty, taskResult.StdErr);
Assert.AreEqual("Expected Output", taskResult.StdOut.Replace(Environment.NewLine, string.Empty));
taskResult.ExitCode.Should().Be(0);
taskResult.StdErr.Should().Be(string.Empty);
taskResult.StdOut.Replace(Environment.NewLine, string.Empty).Should().Be("Expected Output");
}
[SkipTestIfNotWindows]
public async Task ExecutesCommandEvenWithLargeStdOutAsync()
{
var isLocated = await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C");
Assert.IsTrue(isLocated);
isLocated.Should().BeTrue();
var largeStringBuilder = new StringBuilder();
// Cmd.exe command limit is in the 8100s
@ -64,16 +67,19 @@ public class CommandLineInvocationServiceTests
}
var taskResult = await this.commandLineService.ExecuteCommandAsync("cmd.exe", default, $"/C echo {largeStringBuilder}");
Assert.AreEqual(0, taskResult.ExitCode);
Assert.AreEqual(string.Empty, taskResult.StdErr);
Assert.IsTrue(taskResult.StdOut.Length > 8099, taskResult.StdOut.Length < 100 ? $"Stdout was '{taskResult.StdOut}', which is shorter than 8100 chars" : $"Length was {taskResult.StdOut.Length}, which is less than 8100");
taskResult.ExitCode.Should().Be(0);
taskResult.StdErr.Should().Be(string.Empty);
taskResult.StdOut.Length.Should()
.BeGreaterThan(
8099,
taskResult.StdOut.Length < 100 ? $"Stdout was '{taskResult.StdOut}', which is shorter than 8100 chars" : $"Length was {taskResult.StdOut.Length}, which is less than 8100");
}
[SkipTestIfNotWindows]
public async Task ExecutesCommandCapturingErrorOutputAsync()
{
var isLocated = await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C");
Assert.IsTrue(isLocated);
isLocated.Should().BeTrue();
var largeStringBuilder = new StringBuilder();
// Pick a command that is "too big" for cmd.
@ -83,16 +89,16 @@ public class CommandLineInvocationServiceTests
}
var taskResult = await this.commandLineService.ExecuteCommandAsync("cmd.exe", default, $"/C echo {largeStringBuilder}");
Assert.AreEqual(1, taskResult.ExitCode);
Assert.IsTrue(taskResult.StdErr.Contains("too long"), $"Expected '{taskResult.StdErr}' to contain 'too long'");
Assert.AreEqual(string.Empty, taskResult.StdOut);
taskResult.ExitCode.Should().Be(1);
taskResult.StdErr.Should().Contain("too long", $"Expected '{taskResult.StdErr}' to contain 'too long'");
taskResult.StdOut.Should().BeEmpty();
}
[SkipTestIfNotWindows]
public async Task ExecutesInAWorkingDirectoryAsync()
{
var isLocated = await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C");
Assert.IsTrue(isLocated);
isLocated.Should().BeTrue();
var tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var tempDirectory = Directory.CreateDirectory(tempDirectoryPath);
@ -105,7 +111,7 @@ public class CommandLineInvocationServiceTests
public async Task ThrowsIfWorkingDirectoryDoesNotExistAsync()
{
var isLocated = await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C");
Assert.IsTrue(isLocated);
isLocated.Should().BeTrue();
var tempDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));

Просмотреть файл

@ -42,8 +42,7 @@ public class ComponentStreamEnumerableTests
},
this.loggerMock.Object);
enumerable.Count()
.Should().Be(2);
enumerable.Should().HaveCount(2);
foreach (var file in enumerable)
{
file.Stream
@ -84,8 +83,7 @@ public class ComponentStreamEnumerableTests
},
this.loggerMock.Object).ToList();
enumerable.Count
.Should().Be(1);
enumerable.Should().ContainSingle();
this.loggerMock.VerifyAll();
}

Просмотреть файл

@ -32,7 +32,7 @@ public class DependencyGraphTests
this.dependencyGraph.AddComponent(componentA, parentComponentId: componentC.Id);
var componentAChildren = this.dependencyGraph.GetDependenciesForComponent(componentA.Id);
componentAChildren.Should().HaveCount(0);
componentAChildren.Should().BeEmpty();
var componentBChildren = this.dependencyGraph.GetDependenciesForComponent(componentB.Id);
componentBChildren.Should().HaveCount(2);
@ -40,11 +40,11 @@ public class DependencyGraphTests
componentBChildren.Should().Contain(componentC.Id);
var componentCChildren = this.dependencyGraph.GetDependenciesForComponent(componentC.Id);
componentCChildren.Should().HaveCount(1);
componentCChildren.Should().ContainSingle();
componentCChildren.Should().Contain(componentA.Id);
var componentDChildren = this.dependencyGraph.GetDependenciesForComponent(componentD.Id);
componentDChildren.Should().HaveCount(1);
componentDChildren.Should().ContainSingle();
componentDChildren.Should().Contain(componentB.Id);
}
@ -112,17 +112,17 @@ public class DependencyGraphTests
this.dependencyGraph.AddComponent(componentF, componentC.Id);
var rootsForComponentA = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id);
rootsForComponentA.Should().HaveCount(1);
rootsForComponentA.Should().ContainSingle();
var rootsForComponentE = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentE.Id);
rootsForComponentE.Should().HaveCount(1);
rootsForComponentE.Should().ContainSingle();
var rootsForComponentB = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id);
rootsForComponentB.Should().HaveCount(1);
rootsForComponentB.Should().ContainSingle();
rootsForComponentB.Should().Contain(componentA.Id);
var rootsForComponentD = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentD.Id);
rootsForComponentD.Should().HaveCount(1);
rootsForComponentD.Should().ContainSingle();
rootsForComponentD.Should().Contain(componentE.Id);
var rootsForComponentC = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id);
@ -146,10 +146,10 @@ public class DependencyGraphTests
this.dependencyGraph.AddComponent(componentB, componentA.Id);
var rootsForComponentA = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id);
rootsForComponentA.Should().HaveCount(0);
rootsForComponentA.Should().BeEmpty();
var rootsForComponentB = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id);
rootsForComponentB.Should().HaveCount(0);
rootsForComponentB.Should().BeEmpty();
}
[TestMethod]
@ -159,7 +159,7 @@ public class DependencyGraphTests
this.dependencyGraph.AddComponent(componentA);
var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id);
aRoots.Should().HaveCount(1);
aRoots.Should().ContainSingle();
aRoots.Should().Contain(componentA.Id);
}
@ -175,7 +175,7 @@ public class DependencyGraphTests
this.dependencyGraph.AddComponent(componentC, componentB.Id);
var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id);
aRoots.Should().HaveCount(1);
aRoots.Should().ContainSingle();
aRoots.Should().Contain(componentA.Id);
var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id);
@ -217,7 +217,7 @@ public class DependencyGraphTests
bRoots.Should().Contain(componentC.Id);
var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id);
cRoots.Should().HaveCount(1);
cRoots.Should().ContainSingle();
cRoots.Should().Contain(componentC.Id);
}
@ -235,17 +235,17 @@ public class DependencyGraphTests
this.dependencyGraph.AddComponent(componentA, componentC.Id);
var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id);
aRoots.Should().HaveCount(1);
aRoots.Should().ContainSingle();
aRoots.Should().Contain(componentC.Id);
((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse();
var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id);
bRoots.Should().HaveCount(1);
bRoots.Should().ContainSingle();
bRoots.Should().Contain(componentC.Id);
((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse();
var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id);
cRoots.Should().HaveCount(1);
cRoots.Should().ContainSingle();
cRoots.Should().Contain(componentC.Id);
((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue();
}
@ -264,17 +264,17 @@ public class DependencyGraphTests
this.dependencyGraph.AddComponent(componentA, componentC.Id);
var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id);
aRoots.Should().HaveCount(1);
aRoots.Should().ContainSingle();
aRoots.Should().Contain(componentC.Id);
((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse();
var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id);
bRoots.Should().HaveCount(1);
bRoots.Should().ContainSingle();
bRoots.Should().Contain(componentC.Id);
((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse();
var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id);
cRoots.Should().HaveCount(1);
cRoots.Should().ContainSingle();
cRoots.Should().Contain(componentC.Id);
((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue();
}
@ -368,7 +368,7 @@ public class DependencyGraphTests
ancestors.Should().Contain(componentB.Id);
ancestors = this.dependencyGraph.GetAncestors(componentB.Id);
ancestors.Should().HaveCount(1);
ancestors.Should().ContainSingle();
ancestors.Should().Contain(componentA.Id);
ancestors = this.dependencyGraph.GetAncestors(componentA.Id);

Просмотреть файл

@ -27,14 +27,14 @@ public class DockerServiceTests
public async Task DockerService_CanPingDockerAsync()
{
var canPingDocker = await this.dockerService.CanPingDockerAsync();
Assert.IsTrue(canPingDocker);
canPingDocker.Should().BeTrue();
}
[SkipTestOnWindows]
public async Task DockerService_CanRunLinuxContainersAsync()
{
var isLinuxContainerModeEnabled = await this.dockerService.CanRunLinuxContainersAsync();
Assert.IsTrue(isLinuxContainerModeEnabled);
isLinuxContainerModeEnabled.Should().BeTrue();
}
[SkipTestOnWindows]
@ -65,7 +65,7 @@ public class DockerServiceTests
var expectedCreatedAt = DateTime.Parse("2021-09-23T23:47:57.442225064Z").ToUniversalTime();
details.Should().NotBeNull();
details.Id.Should().BeGreaterThan(0);
details.Id.Should().BePositive();
details.ImageId.Should().BeEquivalentTo(expectedImageId);
details.CreatedAt.ToUniversalTime().Should().Be(expectedCreatedAt);
details.BaseImageDigest.Should().Be("sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412");

Просмотреть файл

@ -1,6 +1,7 @@
namespace Microsoft.ComponentDetection.Common.Tests;
using System;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
@ -25,17 +26,17 @@ public class EnvironmentVariableServiceTests
[TestMethod]
public void DoesEnvironmentVariableExist_ChecksAreCaseInsensitive()
{
Assert.IsFalse(this.testSubject.DoesEnvironmentVariableExist("THIS_ENVIRONMENT_VARIABLE_DOES_NOT_EXIST"));
this.testSubject.DoesEnvironmentVariableExist("THIS_ENVIRONMENT_VARIABLE_DOES_NOT_EXIST").Should().BeFalse();
Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar));
Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToLower()));
Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToUpper()));
this.testSubject.DoesEnvironmentVariableExist(MyEnvVar).Should().BeTrue();
this.testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToLower()).Should().BeTrue();
this.testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToUpper()).Should().BeTrue();
}
[TestMethod]
public void GetEnvironmentVariable_returnNullIfVariableDoesNotExist()
{
Assert.IsNull(this.testSubject.GetEnvironmentVariable("NonExistentVar"));
this.testSubject.GetEnvironmentVariable("NonExistentVar").Should().BeNull();
}
[TestMethod]
@ -45,8 +46,8 @@ public class EnvironmentVariableServiceTests
string envVariableValue = nameof(envVariableValue);
Environment.SetEnvironmentVariable(envVariableKey, envVariableValue);
var result = this.testSubject.GetEnvironmentVariable(envVariableKey);
Assert.IsNotNull(result);
Assert.AreEqual(envVariableValue, result);
result.Should().NotBeNull();
envVariableValue.Should().Be(result);
Environment.SetEnvironmentVariable(envVariableKey, null);
}
@ -59,8 +60,8 @@ public class EnvironmentVariableServiceTests
Environment.SetEnvironmentVariable(envVariableKey2, "tRuE");
var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1);
var result2 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1);
Assert.IsTrue(result1);
Assert.IsTrue(result2);
result1.Should().BeTrue();
result2.Should().BeTrue();
Environment.SetEnvironmentVariable(envVariableKey1, null);
Environment.SetEnvironmentVariable(envVariableKey2, null);
}
@ -74,8 +75,8 @@ public class EnvironmentVariableServiceTests
Environment.SetEnvironmentVariable(envVariableKey2, "fAlSe");
var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1);
var result2 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1);
Assert.IsFalse(result1);
Assert.IsFalse(result2);
result1.Should().BeFalse();
result2.Should().BeFalse();
Environment.SetEnvironmentVariable(envVariableKey1, null);
Environment.SetEnvironmentVariable(envVariableKey2, null);
}
@ -88,8 +89,8 @@ public class EnvironmentVariableServiceTests
Environment.SetEnvironmentVariable(envVariableKey1, "notABoolean");
var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1);
var result2 = this.testSubject.IsEnvironmentVariableValueTrue(nonExistentKey);
Assert.IsFalse(result1);
Assert.IsFalse(result2);
result1.Should().BeFalse();
result2.Should().BeFalse();
Environment.SetEnvironmentVariable(envVariableKey1, null);
}
}

Просмотреть файл

@ -4,6 +4,7 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@ -35,11 +36,11 @@ public class FileEnumerationTests
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.AreEqual(48, foundFiles.Count);
foundFiles.Should().HaveCount(48);
}
else
{
Assert.AreEqual(24, foundFiles.Count);
foundFiles.Should().HaveCount(24);
}
}
}

Просмотреть файл

@ -5,6 +5,7 @@
</ItemGroup>
<ItemGroup Label="Package References">
<PackageReference Include="FluentAssertions.Analyzers" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="System.Threading.Tasks.Dataflow" />