diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/CondaLockComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/CondaLockComponentDetectorTests.cs index da251afd0..d404fd56b 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/CondaLockComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/CondaLockComponentDetectorTests.cs @@ -3,6 +3,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Detectors.Poetry; @@ -87,7 +88,7 @@ public async Task CondaComponentDetector_TestCondaLockFileAsync() var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); // packages from the conda section this.AssertCondaLockComponentNameAndVersion(detectedComponents, "conda-lock", "2.1.0"); @@ -97,26 +98,24 @@ public async Task CondaComponentDetector_TestCondaLockFileAsync() this.AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2023.5.7"); this.AssertPipComponentNameAndVersion(detectedComponents, "requests", "2.31.0"); - Assert.AreEqual(4, detectedComponents.Count()); + detectedComponents.Should().HaveCount(4); } private void AssertCondaLockComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) { - Assert.IsNotNull( - detectedComponents.SingleOrDefault(c => + detectedComponents.SingleOrDefault(c => c.Component is CondaComponent component && component.Name.Equals(name) && - component.Version.Equals(version)), + component.Version.Equals(version)).Should().NotBeNull( $"Component with name {name} and version {version} was not found"); } private void AssertPipComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) { - Assert.IsNotNull( - detectedComponents.SingleOrDefault(c => + detectedComponents.SingleOrDefault(c => c.Component is PipComponent component && component.Name.Equals(name) && - component.Version.Equals(version)), + component.Version.Equals(version)).Should().NotBeNull( $"Component with name {name} and version {version} was not found"); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs index 8fc5f3adc..9d96b793a 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs @@ -48,16 +48,16 @@ public async Task TestGoModDetectorWithValidFile_ReturnsSuccessfullyAsync() .WithFile("go.mod", goMod) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(4, detectedComponents.Count()); + detectedComponents.Should().HaveCount(4); var discoveredComponents = detectedComponents.ToArray(); - discoveredComponents.Where(component => component.Component.Id == "github.com/Azure/azure-pipeline-go v0.2.1 - Go").Count().Should().Be(1); - discoveredComponents.Where(component => component.Component.Id == "github.com/dgrijalva/jwt-go v3.2.0+incompatible - Go").Count().Should().Be(1); - discoveredComponents.Where(component => component.Component.Id == "gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 - Go").Count().Should().Be(1); - discoveredComponents.Where(component => component.Component.Id == "github.com/kr/pretty v0.1.0 - Go").Count().Should().Be(1); + discoveredComponents.Where(component => component.Component.Id == "github.com/Azure/azure-pipeline-go v0.2.1 - Go").Should().ContainSingle(); + discoveredComponents.Where(component => component.Component.Id == "github.com/dgrijalva/jwt-go v3.2.0+incompatible - Go").Should().ContainSingle(); + discoveredComponents.Where(component => component.Component.Id == "gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 - Go").Should().ContainSingle(); + discoveredComponents.Where(component => component.Component.Id == "github.com/kr/pretty v0.1.0 - Go").Should().ContainSingle(); } [TestMethod] @@ -79,23 +79,23 @@ public async Task TestGoSumDetectorWithValidFile_ReturnsSuccessfullyAsync() .WithFile("go.sum", goSum) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(6, detectedComponents.Count()); + detectedComponents.Should().HaveCount(6); var typedComponents = detectedComponents.Select(d => d.Component).ToList(); - Assert.IsTrue(typedComponents.Contains( - new GoComponent("github.com/golang/mock", "v1.1.1", "h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A="))); - Assert.IsTrue(typedComponents.Contains( - new GoComponent("github.com/golang/mock", "v1.2.0", "h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A="))); - Assert.IsTrue(typedComponents.Contains( - new GoComponent("github.com/golang/protobuf", "v0.0.0-20161109072736-4bd1920723d7", "h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U="))); - Assert.IsTrue(typedComponents.Contains( - new GoComponent("github.com/golang/protobuf", "v1.2.0", "h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U="))); - Assert.IsTrue(typedComponents.Contains( - new GoComponent("github.com/golang/protobuf", "v1.3.1", "h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg="))); - Assert.IsTrue(typedComponents.Contains( - new GoComponent("github.com/golang/protobuf", "v1.3.2", "h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs="))); + typedComponents.Should().Contain( + new GoComponent("github.com/golang/mock", "v1.1.1", "h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=")); + typedComponents.Should().Contain( + new GoComponent("github.com/golang/mock", "v1.2.0", "h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=")); + typedComponents.Should().Contain( + new GoComponent("github.com/golang/protobuf", "v0.0.0-20161109072736-4bd1920723d7", "h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=")); + typedComponents.Should().Contain( + new GoComponent("github.com/golang/protobuf", "v1.2.0", "h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=")); + typedComponents.Should().Contain( + new GoComponent("github.com/golang/protobuf", "v1.3.1", "h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=")); + typedComponents.Should().Contain( + new GoComponent("github.com/golang/protobuf", "v1.3.2", "h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=")); } [TestMethod] @@ -115,16 +115,16 @@ public async Task TestGoModDetector_MultipleSpaces_ReturnsSuccessfullyAsync() .WithFile("go.mod", goMod) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(4, detectedComponents.Count()); + detectedComponents.Should().HaveCount(4); var discoveredComponents = detectedComponents.ToArray(); - discoveredComponents.Where(component => component.Component.Id == "github.com/Azure/azure-pipeline-go v0.2.1 - Go").Count().Should().Be(1); - discoveredComponents.Where(component => component.Component.Id == "github.com/dgrijalva/jwt-go v3.2.0+incompatible - Go").Count().Should().Be(1); - discoveredComponents.Where(component => component.Component.Id == "gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 - Go").Count().Should().Be(1); - discoveredComponents.Where(component => component.Component.Id == "github.com/kr/pretty v0.1.0 - Go").Count().Should().Be(1); + discoveredComponents.Where(component => component.Component.Id == "github.com/Azure/azure-pipeline-go v0.2.1 - Go").Should().ContainSingle(); + discoveredComponents.Where(component => component.Component.Id == "github.com/dgrijalva/jwt-go v3.2.0+incompatible - Go").Should().ContainSingle(); + discoveredComponents.Where(component => component.Component.Id == "gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 - Go").Should().ContainSingle(); + discoveredComponents.Where(component => component.Component.Id == "github.com/kr/pretty v0.1.0 - Go").Should().ContainSingle(); } [TestMethod] @@ -154,11 +154,11 @@ public async Task TestGoModDetector_ComponentsWithMultipleLocations_ReturnsSucce .WithFile("go.mod", goMod2, fileLocation: Path.Join(Path.GetTempPath(), "another-location", "go.mod")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(4, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(4); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); - Assert.IsTrue(dependencyGraphs.Keys.Count() == 2); + dependencyGraphs.Keys.Should().HaveCount(2); var firstGraph = dependencyGraphs.Values.First(); var secondGraph = dependencyGraphs.Values.Skip(1).First(); @@ -179,8 +179,8 @@ four score and seven bugs ago .WithFile("go.mod", invalidGoMod) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -257,10 +257,10 @@ public async Task TestGoSumDetection_TwoEntriesForTheSameComponent_ReturnsSucces .WithFile("go.sum", goSum) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); } [TestMethod] @@ -282,14 +282,14 @@ public async Task TestGoModDetector_DetectorOnlyDetectInsideRequireSectionAsync( .WithFile("go.mod", goMod) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(2, detectedComponents.Count()); + detectedComponents.Should().HaveCount(2); var discoveredComponents = detectedComponents.ToArray(); - discoveredComponents.Where(component => component.Component.Id == "github.com/Azure/azure-pipeline-go v0.2.1 - Go").Count().Should().Be(1); - discoveredComponents.Where(component => component.Component.Id == "github.com/kr/pretty v0.1.0 - Go").Count().Should().Be(1); + discoveredComponents.Where(component => component.Component.Id == "github.com/Azure/azure-pipeline-go v0.2.1 - Go").Should().ContainSingle(); + discoveredComponents.Where(component => component.Component.Id == "github.com/kr/pretty v0.1.0 - Go").Should().ContainSingle(); } [TestMethod] @@ -402,15 +402,15 @@ public async Task TestGoDetector_GoGraphHappyPathAsync() .WithFile("go.mod", string.Empty) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(4, detectedComponents.Count()); - detectedComponents.Where(component => component.Component.Id == "other v1.0.0 - Go").Should().HaveCount(0); - detectedComponents.Where(component => component.Component.Id == "other v1.2.0 - Go").Should().HaveCount(1); - detectedComponents.Where(component => component.Component.Id == "some-package v1.2.3 - Go").Should().HaveCount(1); - detectedComponents.Where(component => component.Component.Id == "test v2.0.0 - Go").Should().HaveCount(1); - detectedComponents.Where(component => component.Component.Id == "a v1.5.0 - Go").Should().HaveCount(1); + detectedComponents.Should().HaveCount(4); + detectedComponents.Should().NotContain(component => component.Component.Id == "other v1.0.0 - Go"); + detectedComponents.Should().ContainSingle(component => component.Component.Id == "other v1.2.0 - Go"); + detectedComponents.Should().ContainSingle(component => component.Component.Id == "some-package v1.2.3 - Go"); + detectedComponents.Should().ContainSingle(component => component.Component.Id == "test v2.0.0 - Go"); + detectedComponents.Should().ContainSingle(component => component.Component.Id == "a v1.5.0 - Go"); } [TestMethod] @@ -464,10 +464,10 @@ public async Task TestGoDetector_GoGraphCyclicDependenciesAsync() .WithFile("go.mod", string.Empty) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(3, detectedComponents.Count()); + detectedComponents.Should().HaveCount(3); } [TestMethod] diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentTests.cs index 755c92e81..319f75391 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentTests.cs @@ -1,6 +1,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -22,10 +23,10 @@ public void TestInitialize() public void ConstructorTest_NameVersion() { var goComponent = new GoComponent(TestName, TestVersion); - Assert.AreEqual(TestName, goComponent.Name); - Assert.AreEqual(TestVersion, goComponent.Version); - Assert.AreEqual(string.Empty, goComponent.Hash); - Assert.AreEqual($"{TestName} {TestVersion} - Go", goComponent.Id); + goComponent.Name.Should().Be(TestName); + goComponent.Version.Should().Be(TestVersion); + goComponent.Hash.Should().Be(string.Empty); + goComponent.Id.Should().Be($"{TestName} {TestVersion} - Go"); } [TestMethod] @@ -46,10 +47,10 @@ public void ConstructorTest_NameVersion_NullName() public void ConstructorTest_NameVersionHash() { var goComponent = new GoComponent(TestName, TestVersion, TestHash); - Assert.AreEqual(TestName, goComponent.Name); - Assert.AreEqual(TestVersion, goComponent.Version); - Assert.AreEqual(TestHash, goComponent.Hash); - Assert.AreEqual($"{TestName} {TestVersion} - Go", goComponent.Id); + goComponent.Name.Should().Be(TestName); + goComponent.Version.Should().Be(TestVersion); + goComponent.Hash.Should().Be(TestHash); + goComponent.Id.Should().Be($"{TestName} {TestVersion} - Go"); } [TestMethod] @@ -79,11 +80,11 @@ public void TestEquals() var goComponent1 = new GoComponent(TestName, TestVersion, TestHash); var goComponent2 = new GoComponent(TestName, TestVersion, TestHash); var goComponent3 = new GoComponent(TestName, TestVersion, Guid.NewGuid().ToString()); - Assert.IsTrue(goComponent1.Equals(goComponent2)); - Assert.IsTrue(((object)goComponent1).Equals(goComponent2)); + goComponent1.Equals(goComponent2).Should().BeTrue(); + ((object)goComponent1).Equals(goComponent2).Should().BeTrue(); - Assert.IsFalse(goComponent1.Equals(goComponent3)); - Assert.IsFalse(((object)goComponent1).Equals(goComponent3)); + goComponent1.Equals(goComponent3).Should().BeFalse(); + ((object)goComponent1).Equals(goComponent3).Should().BeFalse(); } [TestMethod] @@ -91,6 +92,6 @@ public void TestGetHashCode() { var goComponent1 = new GoComponent(TestName, TestVersion, TestHash); var goComponent2 = new GoComponent(TestName, TestVersion, TestHash); - Assert.IsTrue(goComponent1.GetHashCode() == goComponent2.GetHashCode()); + goComponent1.GetHashCode().Should().Be(goComponent2.GetHashCode()); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs index dc67b1c11..7ab6fb7f8 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs @@ -22,8 +22,8 @@ public async Task TestGradleDetectorWithNoFiles_ReturnsSuccessfullyAsync() var (scanResult, componentRecorder) = await this.DetectorTestUtility .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -38,23 +38,23 @@ public async Task TestGradleDetectorWithValidFile_DetectsComponentsSuccessfullyA .WithFile("gradle.lockfile", validFileOne) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var discoveredComponents = componentRecorder.GetDetectedComponents().Select(c => (MavenComponent)c.Component).OrderBy(c => c.ArtifactId).ToList(); - Assert.AreEqual(3, discoveredComponents.Count); + discoveredComponents.Should().HaveCount(3); - Assert.AreEqual("org.springframework", discoveredComponents[0].GroupId); - Assert.AreEqual("spring-beans", discoveredComponents[0].ArtifactId); - Assert.AreEqual("5.0.5.RELEASE", discoveredComponents[0].Version); + discoveredComponents[0].GroupId.Should().Be("org.springframework"); + discoveredComponents[0].ArtifactId.Should().Be("spring-beans"); + discoveredComponents[0].Version.Should().Be("5.0.5.RELEASE"); - Assert.AreEqual("org.springframework", discoveredComponents[1].GroupId); - Assert.AreEqual("spring-core", discoveredComponents[1].ArtifactId); - Assert.AreEqual("5.0.5.RELEASE", discoveredComponents[1].Version); + discoveredComponents[1].GroupId.Should().Be("org.springframework"); + discoveredComponents[1].ArtifactId.Should().Be("spring-core"); + discoveredComponents[1].Version.Should().Be("5.0.5.RELEASE"); - Assert.AreEqual("org.springframework", discoveredComponents[2].GroupId); - Assert.AreEqual("spring-jcl", discoveredComponents[2].ArtifactId); - Assert.AreEqual("5.0.5.RELEASE", discoveredComponents[2].Version); + discoveredComponents[2].GroupId.Should().Be("org.springframework"); + discoveredComponents[2].ArtifactId.Should().Be("spring-jcl"); + discoveredComponents[2].Version.Should().Be("5.0.5.RELEASE"); } [TestMethod] @@ -69,24 +69,24 @@ public async Task TestGradleDetectorWithValidSingleLockfilePerProject_DetectsCom .WithFile("gradle.lockfile", validFileOne) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); var discoveredComponents = detectedComponents.Select(c => (MavenComponent)c.Component).OrderBy(c => c.ArtifactId).ToList(); - Assert.AreEqual(3, discoveredComponents.Count); + discoveredComponents.Should().HaveCount(3); - Assert.AreEqual("org.springframework", discoveredComponents[0].GroupId); - Assert.AreEqual("spring-beans", discoveredComponents[0].ArtifactId); - Assert.AreEqual("5.0.5.RELEASE", discoveredComponents[0].Version); + discoveredComponents[0].GroupId.Should().Be("org.springframework"); + discoveredComponents[0].ArtifactId.Should().Be("spring-beans"); + discoveredComponents[0].Version.Should().Be("5.0.5.RELEASE"); - Assert.AreEqual("org.springframework", discoveredComponents[1].GroupId); - Assert.AreEqual("spring-core", discoveredComponents[1].ArtifactId); - Assert.AreEqual("5.0.5.RELEASE", discoveredComponents[1].Version); + discoveredComponents[1].GroupId.Should().Be("org.springframework"); + discoveredComponents[1].ArtifactId.Should().Be("spring-core"); + discoveredComponents[1].Version.Should().Be("5.0.5.RELEASE"); - Assert.AreEqual("org.springframework", discoveredComponents[2].GroupId); - Assert.AreEqual("spring-jcl", discoveredComponents[2].ArtifactId); - Assert.AreEqual("5.0.5.RELEASE", discoveredComponents[2].Version); + discoveredComponents[2].GroupId.Should().Be("org.springframework"); + discoveredComponents[2].ArtifactId.Should().Be("spring-jcl"); + discoveredComponents[2].Version.Should().Be("5.0.5.RELEASE"); } [TestMethod] @@ -109,11 +109,11 @@ public async Task TestGradleDetectorWithValidFiles_ReturnsSuccessfullyAsync() .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(7, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(7); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); - dependencyGraphs.Keys.Count().Should().Be(2); + dependencyGraphs.Keys.Should().HaveCount(2); var graph1 = dependencyGraphs.Values.Single(dependencyGraph => dependencyGraph.GetComponents().Count() == 3); var graph2 = dependencyGraphs.Values.Single(dependencyGraph => dependencyGraph.GetComponents().Count() == 5); @@ -154,16 +154,16 @@ public async Task TestGradleDetector_SameComponentDifferentLocations_DifferentLo .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(1); componentRecorder.ForOneComponent(componentRecorder.GetDetectedComponents().First().Component.Id, x => { - Enumerable.Count(x.AllFileLocations).Should().Be(2); + x.AllFileLocations.Should().HaveCount(2); }); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); - dependencyGraphs.Keys.Count().Should().Be(2); + dependencyGraphs.Keys.Should().HaveCount(2); var graph1 = dependencyGraphs.Values.First(); var graph2 = dependencyGraphs.Values.Skip(1).First(); @@ -192,11 +192,11 @@ four score and seven bugs ago .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(5, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(5); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); - dependencyGraphs.Keys.Count().Should().Be(1); + dependencyGraphs.Keys.Should().ContainSingle(); var graph2 = dependencyGraphs.Values.Single(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs index 938d1d159..03f4236bb 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs @@ -34,8 +34,8 @@ public async Task IfAntIsNotAvailableThenExitDetectorGracefullyAsync() var (detectorResult, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); - Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 0); - Assert.AreEqual(detectorResult.ResultCode, ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); + detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); } [TestMethod] @@ -54,22 +54,22 @@ public async Task AntAvailableHappyPathAsync() var (detectorResult, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); var detectedComponents = componentRecorder.GetDetectedComponents(); // IsDevelopmentDependency = true in componentRecorder but null in detectedComponents... why? - Assert.AreEqual(3, detectedComponents.Count()); - Assert.AreEqual(ProcessingResultCode.Success, detectorResult.ResultCode); + detectedComponents.Should().HaveCount(3); + detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); foreach (var detectedComponent in detectedComponents) { var dm = (MavenComponent)detectedComponent.Component; - Assert.AreEqual(dm.ArtifactId.Replace('a', 'g'), dm.GroupId); - Assert.AreEqual(dm.GroupId.Replace('g', 'a'), dm.ArtifactId); - Assert.AreEqual(string.Format("{0}.{0}.{0}", dm.ArtifactId.Substring(1, 1)), dm.Version); - Assert.AreEqual(ComponentType.Maven, dm.Type); + dm.GroupId.Should().Be(dm.ArtifactId.Replace('a', 'g')); + dm.ArtifactId.Should().Be(dm.GroupId.Replace('g', 'a')); + dm.Version.Should().Be(string.Format("{0}.{0}.{0}", dm.ArtifactId.Substring(1, 1))); + dm.Type.Should().Be(ComponentType.Maven); // "Detector should not populate DetectedComponent.DevelopmentDependency" - see ComponentRecorder.cs. Hence we get null not true (for d1g:d1a:1.1.1) or false here. - Assert.IsNull(detectedComponent.DevelopmentDependency); + detectedComponent.DevelopmentDependency.Should().BeNull(); // "Detector should not populate DetectedComponent.DependencyRoots!" - Assert.IsNull(detectedComponent.DependencyRoots); + detectedComponent.DependencyRoots.Should().BeNull(); } } @@ -104,8 +104,8 @@ public async Task IvyDependencyGraphAsync() var (detectorResult, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); var detectedComponents = componentRecorder.GetDetectedComponents(); // IsDevelopmentDependency = true in componentRecorder but null in detectedComponents... why? - Assert.AreEqual(3, detectedComponents.Count()); - Assert.AreEqual(ProcessingResultCode.Success, detectorResult.ResultCode); + detectedComponents.Should().HaveCount(3); + detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); // There is only one graph var dependencyGraph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); @@ -140,12 +140,12 @@ private void IvyHappyPath(string content) IvyDetector.AdditionalValidCommands, It.IsAny())).Callback((string cmd, IEnumerable cmd2, string[] parameters) => { - Assert.AreEqual(parameters[0], "-buildfile"); + parameters.Should().HaveElementAt(0, "-buildfile"); var workingDir = parameters[1].Replace("build.xml", string.Empty); Directory.CreateDirectory(Path.Combine(workingDir, "target")); var jsonFileOutputPath = Path.Combine(workingDir, "target", "RegisterUsage.json"); File.WriteAllText(jsonFileOutputPath, content); - Assert.AreEqual(parameters[2], "resolve-dependencies"); + parameters.Should().HaveElementAt(2, "resolve-dependencies"); }).ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs index 541266944..731509578 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs @@ -77,7 +77,7 @@ public async Task TestLinuxContainerDetectorAsync() detectedComponents.Should().ContainSingle(); detectedComponents.First().Component.Id.Should().Be(BashPackageId); scanResult.ContainerDetails.Should().ContainSingle(); - detectedComponents.All(dc => dc.ContainerDetailIds.Contains(scanResult.ContainerDetails.First().Id)).Should().BeTrue(); + detectedComponents.Should().OnlyContain(dc => dc.ContainerDetailIds.Contains(scanResult.ContainerDetails.First().Id)); componentRecorder.GetDetectedComponents().Select(detectedComponent => detectedComponent.Component.Id) .Should().BeEquivalentTo(detectedComponents.Select(detectedComponent => detectedComponent.Component.Id)); } @@ -102,8 +102,8 @@ public async Task TestLinuxContainerDetector_CantRunLinuxContainersAsync() var detectedComponents = componentRecorder.GetDetectedComponents().ToList(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - detectedComponents.Should().HaveCount(0); - scanResult.ContainerDetails.Should().HaveCount(0); + detectedComponents.Should().BeEmpty(); + scanResult.ContainerDetails.Should().BeEmpty(); this.mockLinuxContainerDetectorLogger.Verify(logger => logger.Log( It.IsAny(), It.IsAny(), @@ -129,8 +129,8 @@ public async Task TestLinuxContainerDetector_TestNullAsync() var detectedComponents = componentRecorder.GetDetectedComponents(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - detectedComponents.Should().HaveCount(0); - scanResult.ContainerDetails.Should().HaveCount(0); + detectedComponents.Should().BeEmpty(); + scanResult.ContainerDetails.Should().BeEmpty(); this.mockLinuxContainerDetectorLogger.Verify(logger => logger.Log( It.IsAny(), It.IsAny(), @@ -158,8 +158,8 @@ public async Task TestLinuxContainerDetector_VerifyLowerCaseAsync() scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); detectedComponents.Should().ContainSingle(); detectedComponents.First().Component.Id.Should().Be(BashPackageId); - scanResult.ContainerDetails.Should().HaveCount(1); - detectedComponents.All(dc => dc.ContainerDetailIds.Contains(scanResult.ContainerDetails.First().Id)).Should().BeTrue(); + scanResult.ContainerDetails.Should().ContainSingle(); + detectedComponents.Should().OnlyContain(dc => dc.ContainerDetailIds.Contains(scanResult.ContainerDetails.First().Id)); } [TestMethod] @@ -179,10 +179,10 @@ public async Task TestLinuxContainerDetector_SameImagePassedMultipleTimesAsync() var detectedComponents = componentRecorder.GetDetectedComponents().ToList(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - scanResult.ContainerDetails.Should().HaveCount(1); - detectedComponents.Should().HaveCount(1); + scanResult.ContainerDetails.Should().ContainSingle(); + detectedComponents.Should().ContainSingle(); detectedComponents.First().Component.Id.Should().Be(BashPackageId); - detectedComponents.All(dc => dc.ContainerDetailIds.Contains(scanResult.ContainerDetails.First().Id)).Should().BeTrue(); + detectedComponents.Should().OnlyContain(dc => dc.ContainerDetailIds.Contains(scanResult.ContainerDetails.First().Id)); this.mockSyftLinuxScanner.Verify(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Once); } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs index 1108f80bf..e90d7e544 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs @@ -60,7 +60,7 @@ public async Task TestLinuxScannerAsync() { var result = (await this.linuxScanner.ScanLinuxAsync("fake_hash", new[] { new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" } }, 0)).First().LinuxComponents; - result.Should().HaveCount(1); + result.Should().ContainSingle(); var package = result.First(); package.Name.Should().Be("test"); package.Version.Should().Be("1.0.0"); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs index 44a43d7e6..759ff36db 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs @@ -1,6 +1,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -17,22 +18,22 @@ public void GenerateDetectedComponentAndIsDeveDependencyAndDependencyScope_Happy var componentAndMetaData = GenerateDetectedComponentAndMetadataFromMavenString("org.apache.maven:maven-artifact:jar:3.6.1-SNAPSHOT:provided"); - Assert.IsNotNull(componentAndMetaData); - Assert.IsNotNull(componentAndMetaData.Component); - Assert.IsNotNull(componentAndMetaData.IsDevelopmentDependency); - Assert.IsNotNull(componentAndMetaData.DependencyScope); + componentAndMetaData.Should().NotBeNull(); + componentAndMetaData.Component.Should().NotBeNull(); + componentAndMetaData.IsDevelopmentDependency.Should().NotBeNull(); + componentAndMetaData.DependencyScope.Should().NotBeNull(); var actualComponent = (MavenComponent)componentAndMetaData.Component.Component; - Assert.IsInstanceOfType(actualComponent, typeof(MavenComponent)); + actualComponent.Should().BeOfType(); var expectedComponent = new MavenComponent("org.apache.maven", "maven-artifact", "3.6.1-SNAPSHOT"); - Assert.AreEqual(expectedComponent.ArtifactId, actualComponent.ArtifactId); - Assert.AreEqual(expectedComponent.GroupId, actualComponent.GroupId); - Assert.AreEqual(expectedComponent.Version, actualComponent.Version); + actualComponent.ArtifactId.Should().Be(expectedComponent.ArtifactId); + actualComponent.GroupId.Should().Be(expectedComponent.GroupId); + actualComponent.Version.Should().Be(expectedComponent.Version); - Assert.IsFalse(componentAndMetaData.IsDevelopmentDependency); - Assert.AreEqual(DependencyScope.MavenProvided, componentAndMetaData.DependencyScope); + componentAndMetaData.IsDevelopmentDependency.Should().BeFalse(); + componentAndMetaData.DependencyScope.Should().Be(DependencyScope.MavenProvided); } [TestMethod] @@ -41,12 +42,12 @@ public void GenerateDetectedComponentAndIsDeveDependencyAndDependencyScope_Defau var componentAndMetaData = GenerateDetectedComponentAndMetadataFromMavenString("org.apache.maven:maven-artifact:jar:3.6.1-SNAPSHOT"); - Assert.IsNotNull(componentAndMetaData); - Assert.IsNotNull(componentAndMetaData.DependencyScope); + componentAndMetaData.Should().NotBeNull(); + componentAndMetaData.DependencyScope.Should().NotBeNull(); var actualComponent = (MavenComponent)componentAndMetaData.Component.Component; - Assert.IsInstanceOfType(actualComponent, typeof(MavenComponent)); - Assert.AreEqual(DependencyScope.MavenCompile, componentAndMetaData.DependencyScope); + actualComponent.Should().BeOfType(); + componentAndMetaData.DependencyScope.Should().Be(DependencyScope.MavenCompile); } [TestMethod] @@ -55,12 +56,12 @@ public void GenerateDetectedComponentAndIsDeveDependencyAndDependencyScope_Disca var componentAndMetaData = GenerateDetectedComponentAndMetadataFromMavenString("org.apache.maven:maven-artifact:jar:3.6.1-SNAPSHOT:provided (optional)"); - Assert.IsNotNull(componentAndMetaData); - Assert.IsNotNull(componentAndMetaData.DependencyScope); + componentAndMetaData.Should().NotBeNull(); + componentAndMetaData.DependencyScope.Should().NotBeNull(); var actualComponent = (MavenComponent)componentAndMetaData.Component.Component; - Assert.IsInstanceOfType(actualComponent, typeof(MavenComponent)); - Assert.AreEqual(DependencyScope.MavenProvided, componentAndMetaData.DependencyScope); + actualComponent.Should().BeOfType(); + componentAndMetaData.DependencyScope.Should().Be(DependencyScope.MavenProvided); } [TestMethod] @@ -69,12 +70,12 @@ public void GenerateDetectedComponentAndIsDeveDependencyAndDependencyScope_Devel var componentAndMetaData = GenerateDetectedComponentAndMetadataFromMavenString("org.apache.maven:maven-artifact:jar:3.6.1-SNAPSHOT:test"); - Assert.IsNotNull(componentAndMetaData); - Assert.IsNotNull(componentAndMetaData.IsDevelopmentDependency); + componentAndMetaData.Should().NotBeNull(); + componentAndMetaData.IsDevelopmentDependency.Should().NotBeNull(); var actualComponent = (MavenComponent)componentAndMetaData.Component.Component; - Assert.IsInstanceOfType(actualComponent, typeof(MavenComponent)); - Assert.IsTrue(componentAndMetaData.IsDevelopmentDependency); + actualComponent.Should().BeOfType(); + componentAndMetaData.IsDevelopmentDependency.Should().BeTrue(); } [TestMethod] @@ -82,6 +83,6 @@ public void GenerateDetectedComponentAndIsDeveDependencyAndDependencyScope_Inval { var ex = Assert.ThrowsException( () => GenerateDetectedComponentAndMetadataFromMavenString("org.apache.maven:maven-artifact:jar:3.6.1-SNAPSHOT:invalidScope")); - Assert.IsTrue(ex.Message.Contains("invalid scope", StringComparison.OrdinalIgnoreCase)); + ex.Message.Contains("invalid scope", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs index 000002713..2fa788050 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs @@ -21,25 +21,25 @@ public void MavenFormat_ExpectedParse() var parser = new MavenStyleDependencyGraphParser(); var parsedGraph = parser.Parse(sampleMavenDependencyTree); - Assert.AreEqual(parsedGraph.Children.Count, 20); - Assert.AreEqual(parsedGraph.Value, "org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT"); + parsedGraph.Children.Should().HaveCount(20); + parsedGraph.Value.Should().Be("org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT"); // Verify a specific interesting path: var mavenCore = parsedGraph.Children.FirstOrDefault(x => x.Value == "org.apache.maven:maven-core:jar:3.6.1-SNAPSHOT:compile"); - Assert.IsNotNull(mavenCore); - Assert.AreEqual(mavenCore.Children.Count, 7); + mavenCore.Should().NotBeNull(); + mavenCore.Children.Should().HaveCount(7); var guice = mavenCore.Children.FirstOrDefault(x => x.Value == "com.google.inject:guice:jar:no_aop:4.2.1:compile"); - Assert.IsNotNull(guice); - Assert.AreEqual(guice.Children.Count, 2); + guice.Should().NotBeNull(); + guice.Children.Should().HaveCount(2); var guava = guice.Children.FirstOrDefault(x => x.Value == "com.google.guava:guava:jar:25.1-android:compile"); - Assert.IsNotNull(guava); - Assert.AreEqual(guava.Children.Count, 5); + guava.Should().NotBeNull(); + guava.Children.Should().HaveCount(5); var animalSnifferAnnotations = guava.Children.FirstOrDefault(x => x.Value == "org.codehaus.mojo:animal-sniffer-annotations:jar:1.14:compile"); - Assert.IsNotNull(animalSnifferAnnotations); - Assert.AreEqual(animalSnifferAnnotations.Children.Count, 0); + animalSnifferAnnotations.Should().NotBeNull(); + animalSnifferAnnotations.Children.Should().BeEmpty(); } [TestMethod] @@ -66,7 +66,7 @@ public void MavenFormat_WithSingleFileComponentRecorder_ExpectedParse() var topLevelComponentDependencies = dependencyGraph.GetDependenciesForComponent(topLevelComponent.Component.Id); topLevelComponentDependencies.Should().HaveCount(20); topLevelComponentDependencies.Should().Contain(mavenCore.Component.Id); - topLevelComponentDependencies.All(componentId => dependencyGraph.IsComponentExplicitlyReferenced(componentId)).Should().BeTrue(); + topLevelComponentDependencies.Should().OnlyContain(componentId => dependencyGraph.IsComponentExplicitlyReferenced(componentId)); var mavenCoreDependencies = dependencyGraph.GetDependenciesForComponent(mavenCore.Component.Id); mavenCoreDependencies.Should().HaveCount(7); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj b/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj index dcf4f2fd0..f85097c66 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj @@ -7,6 +7,7 @@ + diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs index b7fa5b965..f74e5c205 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs @@ -36,8 +36,8 @@ public async Task IfMavenIsNotAvailableThenExitDetectorGracefullyAsync() var (detectorResult, componentRecorder) = await this.DetectorTestUtility .ExecuteDetectorAsync(); - Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 0); - Assert.AreEqual(detectorResult.ResultCode, ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); + detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); } [TestMethod] @@ -51,15 +51,15 @@ public async Task MavenAvailableHappyPathAsync() var (detectorResult, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(detectedComponents.Count(), 1); - Assert.AreEqual(detectorResult.ResultCode, ProcessingResultCode.Success); + detectedComponents.Should().ContainSingle(); + detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); var mavenComponent = detectedComponents.First().Component as MavenComponent; var splitComponent = componentString.Split(':'); - Assert.AreEqual(splitComponent[0], mavenComponent.GroupId); - Assert.AreEqual(splitComponent[1], mavenComponent.ArtifactId); - Assert.AreEqual(splitComponent[3], mavenComponent.Version); - Assert.AreEqual(ComponentType.Maven, mavenComponent.Type); + splitComponent.Should().HaveElementAt(0, mavenComponent.GroupId); + splitComponent.Should().HaveElementAt(1, mavenComponent.ArtifactId); + splitComponent.Should().HaveElementAt(3, mavenComponent.Version); + mavenComponent.Type.Should().Be(ComponentType.Maven); } [TestMethod] @@ -103,14 +103,14 @@ public async Task MavenRootsAsync() var (detectorResult, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(detectedComponents.Count(), 3); - Assert.AreEqual(detectorResult.ResultCode, ProcessingResultCode.Success); + detectedComponents.Should().HaveCount(3); + detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); var splitComponent = componentString.Split(':'); var splitChildComponent = childComponentString.Split(':'); var mavenComponent = detectedComponents.FirstOrDefault(x => (x.Component as MavenComponent).ArtifactId == splitChildComponent[1]); - Assert.IsNotNull(mavenComponent); + mavenComponent.Should().NotBeNull(); componentRecorder.AssertAllExplicitlyReferencedComponents( mavenComponent.Component.Id, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs index f2ad9b2cf..ccfb6eba3 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Detectors.Npm; @@ -28,12 +29,12 @@ public async Task TestNpmDetector_NameAndVersionDetectedAsync() var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); - Assert.AreEqual(detectedComponents.First().Component.Type, ComponentType.Npm); - Assert.AreEqual(((NpmComponent)detectedComponents.First().Component).Name, componentName); - Assert.AreEqual(((NpmComponent)detectedComponents.First().Component).Version, version); + detectedComponents.Should().ContainSingle(); + ComponentType.Npm.Should().Be(detectedComponents.First().Component.Type); + componentName.Should().Be(((NpmComponent)detectedComponents.First().Component).Name); + version.Should().Be(((NpmComponent)detectedComponents.First().Component).Version); } [TestMethod] @@ -46,12 +47,12 @@ public async Task TestNpmDetector_AuthorNameAndEmailDetected_AuthorInJsonFormatA var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.AreEqual(authorName, ((NpmComponent)detectedComponents.First().Component).Author.Name); - Assert.AreEqual(authorEmail, ((NpmComponent)detectedComponents.First().Component).Author.Email); + ((NpmComponent)detectedComponents.First().Component).Author.Name.Should().Be(authorName); + ((NpmComponent)detectedComponents.First().Component).Author.Email.Should().Be(authorEmail); } [TestMethod] @@ -64,12 +65,12 @@ public async Task TestNpmDetector_AuthorNameDetectedWhenEmailIsNotPresent_Author var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.AreEqual(authorName, ((NpmComponent)detectedComponents.First().Component).Author.Name); - Assert.IsNull(((NpmComponent)detectedComponents.First().Component).Author.Email); + ((NpmComponent)detectedComponents.First().Component).Author.Name.Should().Be(authorName); + ((NpmComponent)detectedComponents.First().Component).Author.Email.Should().BeNull(); } [TestMethod] @@ -84,12 +85,12 @@ public async Task TestNpmDetector_AuthorNameAndAuthorEmailDetected_WhenAuthorNam var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.AreEqual(authorName, ((NpmComponent)detectedComponents.First().Component).Author.Name); - Assert.AreEqual(authorEmail, ((NpmComponent)detectedComponents.First().Component).Author.Email); + ((NpmComponent)detectedComponents.First().Component).Author.Name.Should().Be(authorName); + ((NpmComponent)detectedComponents.First().Component).Author.Email.Should().Be(authorEmail); } [TestMethod] @@ -103,12 +104,12 @@ public async Task TestNpmDetector_AuthorNameDetected_WhenEmailNotPresentAndUrlIs var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.AreEqual(authorName, ((NpmComponent)detectedComponents.First().Component).Author.Name); - Assert.IsNull(((NpmComponent)detectedComponents.First().Component).Author.Email); + ((NpmComponent)detectedComponents.First().Component).Author.Name.Should().Be(authorName); + ((NpmComponent)detectedComponents.First().Component).Author.Email.Should().BeNull(); } [TestMethod] @@ -123,11 +124,11 @@ public async Task TestNpmDetector_AuthorNull_WhenAuthorMalformed_AuthorAsSingleS var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.IsNull(((NpmComponent)detectedComponents.First().Component).Author); + ((NpmComponent)detectedComponents.First().Component).Author.Should().BeNull(); } [TestMethod] @@ -141,12 +142,12 @@ public async Task TestNpmDetector_AuthorNameDetected_WhenEmailNotPresentAndUrlNo var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.AreEqual(authorName, ((NpmComponent)detectedComponents.First().Component).Author.Name); - Assert.IsNull(((NpmComponent)detectedComponents.First().Component).Author.Email); + ((NpmComponent)detectedComponents.First().Component).Author.Name.Should().Be(authorName); + ((NpmComponent)detectedComponents.First().Component).Author.Email.Should().BeNull(); } [TestMethod] @@ -161,12 +162,12 @@ public async Task TestNpmDetector_AuthorNameAndAuthorEmailDetected_WhenUrlNotPre .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.AreEqual(authorName, ((NpmComponent)detectedComponents.First().Component).Author.Name); - Assert.AreEqual(authorEmail, ((NpmComponent)detectedComponents.First().Component).Author.Email); + ((NpmComponent)detectedComponents.First().Component).Author.Name.Should().Be(authorName); + ((NpmComponent)detectedComponents.First().Component).Author.Email.Should().Be(authorEmail); } [TestMethod] @@ -181,11 +182,11 @@ public async Task TestNpmDetector_NullAuthor_WhenAuthorNameIsNullOrEmpty_AuthorA .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.IsNull(((NpmComponent)detectedComponents.First().Component).Author); + ((NpmComponent)detectedComponents.First().Component).Author.Should().BeNull(); } [TestMethod] @@ -200,20 +201,20 @@ public async Task TestNpmDetector_NullAuthor_WhenAuthorNameIsNullOrEmpty_AuthorA .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); AssertDetectedComponentCount(detectedComponents, 1); AssertNpmComponent(detectedComponents); - Assert.IsNull(((NpmComponent)detectedComponents.First().Component).Author); + ((NpmComponent)detectedComponents.First().Component).Author.Should().BeNull(); } private static void AssertDetectedComponentCount(IEnumerable detectedComponents, int expectedCount) { - Assert.AreEqual(expectedCount, detectedComponents.Count()); + detectedComponents.Should().HaveCount(expectedCount); } private static void AssertNpmComponent(IEnumerable detectedComponents) { - Assert.AreEqual(detectedComponents.First().Component.Type, ComponentType.Npm); + detectedComponents.First().Component.Type.Should().Be(ComponentType.Npm); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs index 7b1cf27e4..bed64d3b3 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs @@ -46,15 +46,15 @@ public async Task TestNpmDetector_PackageLockReturnsValidAsync() .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(4, detectedComponents.Count()); + detectedComponents.Should().HaveCount(4); foreach (var component in detectedComponents) { componentRecorder.AssertAllExplicitlyReferencedComponents( component.Component.Id, parentComponent0 => parentComponent0.Name == componentName0 && parentComponent0.Version == version0); - Assert.IsFalse(string.IsNullOrWhiteSpace(((NpmComponent)component.Component).Hash)); + ((NpmComponent)component.Component).Hash.Should().NotBeNullOrWhiteSpace(); } } @@ -72,8 +72,8 @@ public async Task TestNpmDetector_MismatchedFilesReturnsEmptyAsync() .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -85,8 +85,8 @@ public async Task TestNpmDetector_MissingPackageJsonReturnsEmptyAsync() .WithFile(packageLockName, packageLockContents, this.packageLockJsonSearchPatterns, fileLocation: packageLockPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -117,10 +117,10 @@ public async Task TestNpmDetector_PackageLockMultiRootAsync() .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(4, detectedComponents.Count()); + detectedComponents.Should().HaveCount(4); var component0 = detectedComponents.FirstOrDefault(x => x.Component.Id.Contains(componentName0)); @@ -181,11 +181,11 @@ public async Task TestNpmDetector_VerifyMultiRoot_DependencyGraphAsync() var npmComponent2Id = new NpmComponent(componentName2, version2).Id; var dependenciesFor0 = graph.GetDependenciesForComponent(npmComponent0Id); - Assert.AreEqual(dependenciesFor0.Count(), 2); + dependenciesFor0.Should().HaveCount(2); var dependenciesFor2 = graph.GetDependenciesForComponent(npmComponent2Id); - Assert.AreEqual(dependenciesFor2.Count(), 1); + dependenciesFor2.Should().ContainSingle(); - Assert.IsTrue(dependenciesFor0.Contains(npmComponent2Id)); + dependenciesFor0.Should().Contain(npmComponent2Id); } [TestMethod] @@ -237,8 +237,8 @@ public async Task TestNpmDetector_EmptyVersionSkippedAsync() .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -290,8 +290,8 @@ public async Task TestNpmDetector_InvalidNameSkippedAsync() .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -353,8 +353,8 @@ public async Task TestNpmDetector_LernaDirectoryAsync() .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern, fileLocation: packageJsonFileLocation) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(2, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(2); } [TestMethod] @@ -408,10 +408,10 @@ public async Task TestNpmDetector_CircularRequirementsResolveAsync() .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(2, detectedComponents.Count()); + detectedComponents.Should().HaveCount(2); foreach (var component in detectedComponents) { @@ -439,10 +439,10 @@ public async Task TestNpmDetector_ShrinkwrapLockReturnsValidAsync() .WithFile(this.packageJsonFileName, packageJsonContents, this.packageJsonSearchPattern) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(4, detectedComponents.Count()); + detectedComponents.Should().HaveCount(4); foreach (var component in detectedComponents) { componentRecorder.AssertAllExplicitlyReferencedComponents( @@ -488,10 +488,10 @@ public async Task TestNpmDetector_IgnoresPackageLocksInSubFoldersAsync() .WithFile(this.packageJsonFileName, packageJsonTemplate2, this.packageJsonSearchPattern, fileLocation: packageJsonUnderNodeModules) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(4, detectedComponents.Count()); + detectedComponents.Should().HaveCount(4); foreach (var component in detectedComponents) { componentRecorder.AssertAllExplicitlyReferencedComponents( diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmLockfile3DetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmLockfile3DetectorTests.cs index 02e160c58..a10d505ec 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmLockfile3DetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmLockfile3DetectorTests.cs @@ -45,15 +45,15 @@ public async Task TestNpmDetector_PackageLockVersion3ReturnsValidAsync() .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(4, detectedComponents.Count()); + detectedComponents.Should().HaveCount(4); foreach (var component in detectedComponents) { componentRecorder.AssertAllExplicitlyReferencedComponents( component.Component.Id, parentComponent0 => parentComponent0.Name == componentName0 && parentComponent0.Version == version0); - Assert.IsFalse(string.IsNullOrWhiteSpace(((NpmComponent)component.Component).Hash)); + ((NpmComponent)component.Component).Hash.Should().NotBeNullOrWhiteSpace(); } } @@ -84,10 +84,10 @@ public async Task TestNpmDetector_PackageLockVersion3NestedReturnsValidAsync() .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents().ToList(); - Assert.AreEqual(4, detectedComponents.Count); + detectedComponents.Should().HaveCount(4); var component0 = detectedComponents.First(x => x.Component.Id.Contains(componentName0)); componentRecorder.AssertAllExplicitlyReferencedComponents( @@ -108,7 +108,7 @@ public async Task TestNpmDetector_PackageLockVersion3NestedReturnsValidAsync() componentRecorder.IsDependencyOfExplicitlyReferencedComponents( component.Component.Id, parentComponent0 => parentComponent0.Name == componentName0 || parentComponent0.Name == componentName1); - Assert.IsFalse(string.IsNullOrWhiteSpace(((NpmComponent)component.Component).Hash)); + ((NpmComponent)component.Component).Hash.Should().NotBeNullOrWhiteSpace(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs index f354b8824..ca3551153 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs @@ -40,12 +40,12 @@ public void TestGetTypedComponent() var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); - Assert.IsNotNull(componentFromJProperty); - Assert.AreEqual(componentFromJProperty.Type, ComponentType.Npm); + componentFromJProperty.Should().NotBeNull(); + componentFromJProperty.Type.Should().Be(ComponentType.Npm); var npmComponent = (NpmComponent)componentFromJProperty; - Assert.AreEqual(npmComponent.Name, "async"); - Assert.AreEqual(npmComponent.Version, "2.3.0"); + npmComponent.Name.Should().Be("async"); + npmComponent.Version.Should().Be("2.3.0"); } [TestMethod] @@ -63,7 +63,7 @@ public void TestGetTypedComponent_FailsOnMalformed() var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); - Assert.IsNull(componentFromJProperty); + componentFromJProperty.Should().BeNull(); } [TestMethod] @@ -79,7 +79,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() var j = JObject.Parse(jsonInvalidCharacter); var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); - Assert.IsNull(componentFromJProperty); + componentFromJProperty.Should().BeNull(); var jsonUrlName = @"{ ""http://thisis/my/packagename"": { @@ -91,7 +91,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() j = JObject.Parse(jsonUrlName); componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); - Assert.IsNull(componentFromJProperty); + componentFromJProperty.Should().BeNull(); var jsonInvalidInitialCharacter1 = @"{ ""_async"": { @@ -103,7 +103,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() j = JObject.Parse(jsonInvalidInitialCharacter1); componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); - Assert.IsNull(componentFromJProperty); + componentFromJProperty.Should().BeNull(); var jsonInvalidInitialCharacter2 = @"{ "".async"": { @@ -115,7 +115,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() j = JObject.Parse(jsonInvalidInitialCharacter2); componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); - Assert.IsNull(componentFromJProperty); + componentFromJProperty.Should().BeNull(); var longPackageName = new string('a', 214); var jsonLongName = $@"{{ @@ -128,18 +128,18 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() j = JObject.Parse(jsonLongName); componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); - Assert.IsNull(componentFromJProperty); + componentFromJProperty.Should().BeNull(); } [TestMethod] public void TestTryParseNpmVersion() { var parsed = NpmComponentUtilities.TryParseNpmVersion("registry.npmjs.org", "archiver", "https://registry.npmjs.org/archiver-2.1.1.tgz", out var parsedVersion); - Assert.IsTrue(parsed); - Assert.AreEqual(parsedVersion.ToString(), "2.1.1"); + parsed.Should().BeTrue(); + parsedVersion.ToString().Should().Be("2.1.1"); parsed = NpmComponentUtilities.TryParseNpmVersion("registry.npmjs.org", "archiver", "notavalidurl", out parsedVersion); - Assert.IsFalse(parsed); + parsed.Should().BeFalse(); } [TestMethod] @@ -173,15 +173,15 @@ public void TestTraverseAndGetRequirementsAndDependencies() NpmComponentUtilities.TraverseAndRecordComponents(currentDependency, singleFileComponentRecorder1, typedComponent, typedComponent); NpmComponentUtilities.TraverseAndRecordComponents(currentDependency, singleFileComponentRecorder2, typedComponent, typedComponent); - Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 1); - Assert.IsNotNull(componentRecorder.GetComponent(typedComponent.Id)); + componentRecorder.GetDetectedComponents().Count().Should().Be(1); + componentRecorder.GetComponent(typedComponent.Id).Should().NotBeNull(); var graph1 = componentRecorder.GetDependencyGraphsByLocation()["/this/is/a/test/path/"]; var graph2 = componentRecorder.GetDependencyGraphsByLocation()["/this/is/a/different/path/"]; - Assert.IsTrue(graph1.GetExplicitReferencedDependencyIds(typedComponent.Id).Contains(typedComponent.Id)); - Assert.IsTrue(graph2.GetExplicitReferencedDependencyIds(typedComponent.Id).Contains(typedComponent.Id)); - Assert.IsFalse(componentRecorder.GetEffectiveDevDependencyValue(typedComponent.Id).GetValueOrDefault(true)); + graph1.GetExplicitReferencedDependencyIds(typedComponent.Id).Contains(typedComponent.Id).Should().BeTrue(); + graph2.GetExplicitReferencedDependencyIds(typedComponent.Id).Contains(typedComponent.Id).Should().BeTrue(); + componentRecorder.GetEffectiveDevDependencyValue(typedComponent.Id).GetValueOrDefault(true).Should().BeFalse(); var json1 = @"{ ""test"": { @@ -200,18 +200,18 @@ public void TestTraverseAndGetRequirementsAndDependencies() NpmComponentUtilities.TraverseAndRecordComponents(currentDependency1, singleFileComponentRecorder2, typedComponent1, typedComponent1); - Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 2); + componentRecorder.GetDetectedComponents().Count().Should().Be(2); - Assert.IsTrue(graph2.GetExplicitReferencedDependencyIds(typedComponent1.Id).Contains(typedComponent1.Id)); - Assert.IsTrue(componentRecorder.GetEffectiveDevDependencyValue(typedComponent1.Id).GetValueOrDefault(false)); + graph2.GetExplicitReferencedDependencyIds(typedComponent1.Id).Contains(typedComponent1.Id).Should().BeTrue(); + componentRecorder.GetEffectiveDevDependencyValue(typedComponent1.Id).GetValueOrDefault(false).Should().BeTrue(); NpmComponentUtilities.TraverseAndRecordComponents(currentDependency1, singleFileComponentRecorder2, typedComponent, typedComponent1, parentComponentId: typedComponent1.Id); - Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 2); + componentRecorder.GetDetectedComponents().Count().Should().Be(2); var explicitlyReferencedDependencyIds = graph2.GetExplicitReferencedDependencyIds(typedComponent.Id); - Assert.IsTrue(explicitlyReferencedDependencyIds.Contains(typedComponent.Id)); - Assert.IsTrue(explicitlyReferencedDependencyIds.Contains(typedComponent1.Id)); - Assert.AreEqual(2, explicitlyReferencedDependencyIds.Count); + explicitlyReferencedDependencyIds.Should().Contain(typedComponent.Id); + explicitlyReferencedDependencyIds.Should().Contain(typedComponent1.Id); + explicitlyReferencedDependencyIds.Should().HaveCount(2); } [TestMethod] diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs index 078d203b9..7fab43336 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs @@ -38,8 +38,8 @@ public async Task TestNuGetDetectorWithNoFiles_ReturnsSuccessfullyAsync() { var (scanResult, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -54,14 +54,14 @@ public async Task TestNugetDetector_ReturnsValidNuspecComponentAsync() .WithFile("*.nuspec", nuspec) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode, "Result code does Not match."); - Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count(), "Componet count does not match"); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success, "Result code does Not match."); + componentRecorder.GetDetectedComponents().Count().Should().Be(1, "Component count does not match"); var detectedComponent = componentRecorder.GetDetectedComponents().First().Component; - Assert.AreEqual(ComponentType.NuGet, detectedComponent.Type); + detectedComponent.Type.Should().Be(ComponentType.NuGet); var nuGetComponent = (NuGetComponent)detectedComponent; - Assert.AreEqual(testComponentName, nuGetComponent.Name, "Component name does not match."); - Assert.AreEqual(testVersion, nuGetComponent.Version, "Component version does not match."); - CollectionAssert.AreEqual(testAuthors, nuGetComponent.Authors, "Authors does not match."); + nuGetComponent.Name.Should().Be(testComponentName, "Component name does not match."); + nuGetComponent.Version.Should().Be(testVersion, "Component version does not match."); + nuGetComponent.Authors.Should().BeEquivalentTo(testAuthors, "Authors does not match."); } [TestMethod] @@ -76,14 +76,14 @@ public async Task TestNugetDetector_ReturnsValidNuspecComponent_SingleAuthorAsyn .WithFile("*.nuspec", nuspec) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode, "Result code does Not match."); - Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count(), "Componet count does not match"); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success, "Result code does Not match."); + componentRecorder.GetDetectedComponents().Count().Should().Be(1, "Component count does not match"); var detectedComponent = componentRecorder.GetDetectedComponents().First().Component; - Assert.AreEqual(ComponentType.NuGet, detectedComponent.Type); + detectedComponent.Type.Should().Be(ComponentType.NuGet); var nuGetComponent = (NuGetComponent)detectedComponent; - Assert.AreEqual(testComponentName, nuGetComponent.Name, "Component name does not match."); - Assert.AreEqual(testVersion, nuGetComponent.Version, "Component version does not match."); - CollectionAssert.AreEqual(testAuthors, nuGetComponent.Authors, "Authors does not match."); + nuGetComponent.Name.Should().Be(testComponentName, "Component name does not match."); + nuGetComponent.Version.Should().Be(testVersion, "Component version does not match."); + nuGetComponent.Authors.Should().BeEquivalentTo(testAuthors, "Authors does not match."); } [TestMethod] @@ -95,8 +95,8 @@ public async Task TestNugetDetector_ReturnsValidNupkgComponentAsync() .WithFile("test.nupkg", nupkg) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(1); } [TestMethod] @@ -110,8 +110,8 @@ public async Task TestNugetDetector_ReturnsValidMixedComponentAsync() .WithFile("test.nupkg", nupkg) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(2, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(2); } [TestMethod] @@ -154,10 +154,10 @@ public async Task TestNugetDetector_ReturnsValidPaketComponentAsync() .AddServiceMock(this.mockLogger) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); // While there are 26 lines in the sample, several dependencies are identical, so there are only 11 matches. - Assert.AreEqual(11, componentRecorder.GetDetectedComponents().Count()); + componentRecorder.GetDetectedComponents().Count().Should().Be(11); // Verify that we stop executing after parsing the paket.lock file. this.mockLogger.Verify( @@ -191,8 +191,8 @@ public async Task TestNugetDetector_HandlesMalformedComponentsInComponentListAsy It.IsAny(), (Func)It.IsAny())); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(2, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(2); } [TestMethod] @@ -267,8 +267,8 @@ public async Task TestNugetDetector_AdditionalDirectoriesAsync() var scanResult = await detector.ExecuteDetectorAsync(new ScanRequest(new DirectoryInfo(sourceDirectoryPath), (name, directoryName) => false, null, new Dictionary(), null, componentRecorder)); directoryWalkerMock.VerifyAll(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(1); } [TestMethod] diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs index 8d24e41dd..880923b88 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs @@ -4,6 +4,7 @@ using System.IO; using System.IO.Compression; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Detectors.NuGet; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -22,7 +23,7 @@ public async Task GetNuspecBytes_FailsOnEmptyStreamAsync() await Assert.ThrowsExceptionAsync(ShouldThrow); // The position should always be reset to 0 - Assert.AreEqual(0, stream.Position); + stream.Position.Should().Be(0); } [TestMethod] @@ -42,7 +43,7 @@ public async Task GetNuspecBytes_FailsOnTooSmallStreamAsync() await Assert.ThrowsExceptionAsync(ShouldThrow); // The position should always be reset to 0 - Assert.AreEqual(0, stream.Position); + stream.Position.Should().Be(0); } [TestMethod] @@ -63,7 +64,7 @@ public async Task GetNuspecBytes_FailsIfNuspecNotPresentAsync() await Assert.ThrowsExceptionAsync(ShouldThrow); // The position should always be reset to 0 - Assert.AreEqual(0, stream.Position); + stream.Position.Should().Be(0); } [TestMethod] @@ -86,14 +87,14 @@ public async Task GetNuspecBytes_ReadsNuspecBytesAsync() var bytes = await NuGetNuspecUtilities.GetNuspecBytesAsync(stream); - Assert.AreEqual(randomBytes.Length, bytes.Length); + bytes.Should().HaveCount(randomBytes.Length); for (var i = 0; i < randomBytes.Length; i++) { - Assert.AreEqual(randomBytes[i], bytes[i]); + bytes.Should().HaveElementAt(i, randomBytes[i]); } // The position should always be reset to 0 - Assert.AreEqual(0, stream.Position); + stream.Position.Should().Be(0); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs index 07c73fe2c..ad25eb1a4 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs @@ -44,13 +44,13 @@ public async Task ScanDirectoryAsync_Base_2_2_VerificationAsync() // Number of unique nodes in ProjectAssetsJson Console.WriteLine(string.Join(",", detectedComponents.Select(x => x.Component.Id))); - Assert.AreEqual(3, detectedComponents.Count()); - Assert.IsNotNull(detectedComponents.Select(x => x.Component).Cast().FirstOrDefault(x => x.Name.Contains("coverlet.msbuild"))); + detectedComponents.Should().HaveCount(3); + detectedComponents.Select(x => x.Component).Cast().FirstOrDefault(x => x.Name.Contains("coverlet.msbuild")).Should().NotBeNull(); - Assert.IsTrue(detectedComponents.All(x => + detectedComponents.Should().OnlyContain(x => componentRecorder.IsDependencyOfExplicitlyReferencedComponents( x.Component.Id, - y => y.Id == x.Component.Id))); + y => y.Id == x.Component.Id)); componentRecorder.ForAllComponents(grouping => Assert.IsTrue(grouping.AllFileLocations.Any(location => location.Contains("Loader.csproj")))); } @@ -67,16 +67,16 @@ public async Task ScanDirectoryAsync_Base_2_2_additional_VerificationAsync() // Number of unique nodes in ProjectAssetsJson Console.WriteLine(string.Join(",", detectedComponents.Select(x => x.Component.Id))); - Assert.AreEqual(26, detectedComponents.Count()); - Assert.IsNotNull(detectedComponents.Select(x => x.Component).Cast().FirstOrDefault(x => x.Name.Contains("Polly"))); - Assert.AreEqual(5, detectedComponents.Select(x => x.Component).Cast().Count(x => x.Name.Contains("System.Composition"))); + detectedComponents.Should().HaveCount(26); + detectedComponents.Select(x => x.Component).Cast().FirstOrDefault(x => x.Name.Contains("Polly")).Should().NotBeNull(); + detectedComponents.Select(x => x.Component).Cast().Count(x => x.Name.Contains("System.Composition")).Should().Be(5); var nugetVersioning = detectedComponents.FirstOrDefault(x => (x.Component as NuGetComponent).Name.Contains("NuGet.DependencyResolver.Core")); - Assert.IsNotNull(nugetVersioning); + nugetVersioning.Should().NotBeNull(); - Assert.IsTrue(componentRecorder.IsDependencyOfExplicitlyReferencedComponents( + componentRecorder.IsDependencyOfExplicitlyReferencedComponents( nugetVersioning.Component.Id, - x => x.Name.Contains("NuGet.ProjectModel"))); + x => x.Name.Contains("NuGet.ProjectModel")).Should().BeTrue(); componentRecorder.ForAllComponents(grouping => Assert.IsTrue(grouping.AllFileLocations.Any(location => location.Contains("Detectors.csproj")))); } @@ -92,8 +92,8 @@ public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_2_2_Verification var ommittedComponentInformationJson = scanResult.AdditionalTelemetryDetails[NuGetProjectModelProjectCentricComponentDetector.OmittedFrameworkComponentsTelemetryKey]; var omittedComponentsWithCount = JsonConvert.DeserializeObject>(ommittedComponentInformationJson); - Assert.IsTrue(omittedComponentsWithCount.Keys.Count > 5, "Ommitted framework assemblies are missing. There should be more than ten, but this is a gut check to make sure we have data."); - Assert.AreEqual(omittedComponentsWithCount["Microsoft.NETCore.App"], 4, "There should be four cases of the NETCore.App library being omitted in the test data."); + (omittedComponentsWithCount.Keys.Count > 5).Should().BeTrue("Ommitted framework assemblies are missing. There should be more than ten, but this is a gut check to make sure we have data."); + omittedComponentsWithCount["Microsoft.NETCore.App"].Should().Be(4, "There should be four cases of the NETCore.App library being omitted in the test data."); } [TestMethod] @@ -116,12 +116,12 @@ public async Task ScanDirectoryAsync_DependencyGraph_2_2_additional_Verification var dependencies = graph.GetDependenciesForComponent(componentDetectionCommon.Component.Id); foreach (var expectedId in expectedDependencyIdsForCompositionTypedParts) { - Assert.IsTrue(dependencies.Contains(expectedId)); + dependencies.Should().Contain(expectedId); } - Assert.AreEqual(dependencies.Count(), expectedDependencyIdsForCompositionTypedParts.Length); + expectedDependencyIdsForCompositionTypedParts.Should().HaveSameCount(dependencies); - Assert.AreEqual(graph.GetComponents().Count(), detectedComponents.Count()); + detectedComponents.Should().HaveCount(graph.GetComponents().Count()); // Top level dependencies look like this: // (we expect all non-proj and non-framework to show up as explicit refs, so those will be absent from the check) @@ -172,7 +172,7 @@ public async Task ScanDirectoryAsync_DependencyGraph_2_2_additional_Verification { var component = detectedComponents.First(x => x.Component.Id == componentId); var expectedExplicitRefValue = expectedExplicitRefs.Contains(((NuGetComponent)component.Component).Name); - Assert.AreEqual(expectedExplicitRefValue, graph.IsComponentExplicitlyReferenced(componentId)); + graph.IsComponentExplicitlyReferenced(componentId).Should().Be(expectedExplicitRefValue); } } @@ -186,14 +186,14 @@ public async Task ScanDirectoryAsync_Base_3_1_VerificationAsync() // Number of unique nodes in ProjectAssetsJson var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(2, detectedComponents.Count()); - Assert.IsNotNull(detectedComponents.Select(x => x.Component).Cast().FirstOrDefault(x => x.Name.Contains("Microsoft.Extensions.DependencyModel"))); + detectedComponents.Should().HaveCount(2); + detectedComponents.Select(x => x.Component).Cast().FirstOrDefault(x => x.Name.Contains("Microsoft.Extensions.DependencyModel")).Should().NotBeNull(); var systemTextJson = detectedComponents.FirstOrDefault(x => (x.Component as NuGetComponent).Name.Contains("System.Text.Json")); - Assert.IsTrue(componentRecorder.IsDependencyOfExplicitlyReferencedComponents( + componentRecorder.IsDependencyOfExplicitlyReferencedComponents( systemTextJson.Component.Id, - x => x.Name.Contains("Microsoft.Extensions.DependencyModel"))); + x => x.Name.Contains("Microsoft.Extensions.DependencyModel")).Should().BeTrue(); componentRecorder.ForAllComponents(grouping => Assert.IsTrue(grouping.AllFileLocations.Any(location => location.Contains("ExtCore.WebApplication.csproj")))); } @@ -210,8 +210,8 @@ public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_3_1_Verification var omittedComponentsWithCount = JsonConvert.DeserializeObject>(ommittedComponentInformationJson); // With 3.X, we don't expect there to be a lot of these, but there are still netstandard libraries present which can bring things into the graph - Assert.AreEqual(omittedComponentsWithCount.Keys.Count, 4, "Ommitted framework assemblies are missing. There should be more than ten, but this is a gut check to make sure we have data."); - Assert.AreEqual(omittedComponentsWithCount["System.Reflection"], 1, "There should be one case of the System.Reflection library being omitted in the test data."); + omittedComponentsWithCount.Keys.Should().HaveCount(4, "Ommitted framework assemblies are missing. There should be more than ten, but this is a gut check to make sure we have data."); + omittedComponentsWithCount["System.Reflection"].Should().Be(1, "There should be one case of the System.Reflection library being omitted in the test data."); } [TestMethod] @@ -236,10 +236,10 @@ public async Task ScanDirectoryAsync_DependencyGraph_3_1_VerificationAsync() var dependencies = graph.GetDependenciesForComponent(componentDetectionCommon.Component.Id); foreach (var expectedId in expectedDependencyIdsForExtensionsDependencyModel) { - Assert.IsTrue(dependencies.Contains(expectedId)); + dependencies.Should().Contain(expectedId); } - Assert.AreEqual(graph.GetComponents().Count(), detectedComponents.Count()); + detectedComponents.Should().HaveCount(graph.GetComponents().Count()); // Top level dependencies look like this: // (we expect all non-proj and non-framework to show up as explicit refs, so those will be absent from the check) @@ -256,7 +256,7 @@ public async Task ScanDirectoryAsync_DependencyGraph_3_1_VerificationAsync() { var component = detectedComponents.First(x => x.Component.Id == componentId); var expectedExplicitRefValue = expectedExplicitRefs.Contains(((NuGetComponent)component.Component).Name); - Assert.AreEqual(expectedExplicitRefValue, graph.IsComponentExplicitlyReferenced(componentId)); + graph.IsComponentExplicitlyReferenced(componentId).Should().Be(expectedExplicitRefValue); } } @@ -279,7 +279,7 @@ public async Task ScanDirectory_NoPackageSpecAsync() var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); - dependencyGraphs.Count.Should().Be(0); + dependencyGraphs.Should().BeEmpty(); } private string Convert22SampleToOSAgnostic(string project_assets) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs index 1ddc83cb6..066d1e1a5 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs @@ -53,7 +53,7 @@ public async Task TestPipDetector_PythonNotInstalledAsync() .WithFile("setup.py", string.Empty) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); this.mockLogger.VerifyAll(); } @@ -62,7 +62,7 @@ public async Task TestPipDetector_PythonInstalledNoFilesAsync() { var (result, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); } [TestMethod] @@ -101,23 +101,23 @@ public async Task TestPipDetector_SetupPyAndRequirementsTxtAsync() .WithFile("requirements.txt", string.Empty) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(8, detectedComponents.Count()); + detectedComponents.Should().HaveCount(8); var pipComponents = detectedComponents.Where(detectedComponent => detectedComponent.Component.Id.Contains("pip")).ToList(); - Assert.AreEqual("1.2.3", ((PipComponent)pipComponents.Single(x => ((PipComponent)x.Component).Name == "z").Component).Version); + ((PipComponent)pipComponents.Single(x => ((PipComponent)x.Component).Name == "z").Component).Version.Should().Be("1.2.3"); foreach (var item in setupPyRoots) { var reference = item.Value; - Assert.AreEqual(reference.Version, ((PipComponent)pipComponents.Single(x => ((PipComponent)x.Component).Name == reference.Name).Component).Version); + ((PipComponent)pipComponents.Single(x => ((PipComponent)x.Component).Name == reference.Name).Component).Version.Should().Be(reference.Version); } var gitComponents = detectedComponents.Where(detectedComponent => detectedComponent.Component.Type == ComponentType.Git); - gitComponents.Count().Should().Be(1); + gitComponents.Should().ContainSingle(); var gitComponent = (GitComponent)gitComponents.Single().Component; gitComponent.RepositoryUrl.Should().Be("https://github.com/example/example"); @@ -157,8 +157,8 @@ public async Task TestPipDetector_ComponentsDedupedAcrossFilesAsync() .WithFile("requirements.txt", string.Empty, fileLocation: Path.Join(Path.GetTempPath(), "TEST", "requirements.txt")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(5, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(5); } [TestMethod] @@ -212,8 +212,8 @@ public async Task TestPipDetector_ComponentRecorderAsync() var discoveredComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(11, discoveredComponents.Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + discoveredComponents.Should().HaveCount(11); var rootIds = new[] { @@ -239,7 +239,7 @@ public async Task TestPipDetector_ComponentRecorderAsync() this.CheckChild(componentRecorder, "dog 2.1 - pip", new[] { "c 1.0 - pip", }); var graphsByLocations = componentRecorder.GetDependencyGraphsByLocation(); - Assert.AreEqual(2, graphsByLocations.Count); + graphsByLocations.Should().HaveCount(2); var graph1ComponentsWithDeps = new Dictionary { @@ -252,8 +252,8 @@ public async Task TestPipDetector_ComponentRecorderAsync() }; var graph1 = graphsByLocations[file1]; - Assert.IsTrue(graph1ComponentsWithDeps.Keys.Take(2).All(graph1.IsComponentExplicitlyReferenced)); - Assert.IsTrue(graph1ComponentsWithDeps.Keys.Skip(2).All(a => !graph1.IsComponentExplicitlyReferenced(a))); + graph1ComponentsWithDeps.Keys.Take(2).All(graph1.IsComponentExplicitlyReferenced).Should().BeTrue(); + graph1ComponentsWithDeps.Keys.Skip(2).Should().OnlyContain(a => !graph1.IsComponentExplicitlyReferenced(a)); this.CheckGraphStructure(graph1, graph1ComponentsWithDeps); var graph2ComponentsWithDeps = new Dictionary @@ -269,38 +269,34 @@ public async Task TestPipDetector_ComponentRecorderAsync() }; var graph2 = graphsByLocations[file2]; - Assert.IsTrue(graph2ComponentsWithDeps.Keys.Take(3).All(graph2.IsComponentExplicitlyReferenced)); - Assert.IsTrue(graph2ComponentsWithDeps.Keys.Skip(3).All(a => !graph2.IsComponentExplicitlyReferenced(a))); + graph2ComponentsWithDeps.Keys.Take(3).All(graph2.IsComponentExplicitlyReferenced).Should().BeTrue(); + graph2ComponentsWithDeps.Keys.Skip(3).Should().OnlyContain(a => !graph2.IsComponentExplicitlyReferenced(a)); this.CheckGraphStructure(graph2, graph2ComponentsWithDeps); } private void CheckGraphStructure(IDependencyGraph graph, Dictionary graphComponentsWithDeps) { var graphComponents = graph.GetComponents().ToArray(); - Assert.AreEqual( + graphComponents.Should().HaveCount( graphComponentsWithDeps.Keys.Count, - graphComponents.Length, $"Expected {graphComponentsWithDeps.Keys.Count} component to be recorded but got {graphComponents.Length} instead!"); foreach (var componentId in graphComponentsWithDeps.Keys) { - Assert.IsTrue( - graphComponents.Contains(componentId), - $"Component `{componentId}` not recorded!"); + graphComponents.Should().Contain( + componentId, $"Component `{componentId}` not recorded!"); var recordedDeps = graph.GetDependenciesForComponent(componentId).ToArray(); var expectedDeps = graphComponentsWithDeps[componentId]; - Assert.AreEqual( + recordedDeps.Should().HaveCount( expectedDeps.Length, - recordedDeps.Length, $"Count missmatch of expected dependencies ({JsonConvert.SerializeObject(expectedDeps)}) and recorded dependencies ({JsonConvert.SerializeObject(recordedDeps)}) for `{componentId}`!"); foreach (var expectedDep in expectedDeps) { - Assert.IsTrue( - recordedDeps.Contains(expectedDep), - $"Expected `{expectedDep}` in the list of dependencies for `{componentId}` but only recorded: {JsonConvert.SerializeObject(recordedDeps)}"); + recordedDeps.Should().Contain( + expectedDep, $"Expected `{expectedDep}` in the list of dependencies for `{componentId}` but only recorded: {JsonConvert.SerializeObject(recordedDeps)}"); } } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs index d695cfa17..2e55fbd0c 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs @@ -1,6 +1,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Collections.Generic; +using FluentAssertions; using Microsoft.ComponentDetection.Detectors.Pip; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -15,13 +16,12 @@ private static void VerifyPipDependencyParsing( { var dependencySpecifier = new PipDependencySpecification(specString, requiresDist); - Assert.AreEqual(referenceDependencySpecification.Name, dependencySpecifier.Name); + dependencySpecifier.Name.Should().Be(referenceDependencySpecification.Name); for (var i = 0; i < referenceDependencySpecification.DependencySpecifiers.Count; i++) { - Assert.AreEqual( - referenceDependencySpecification.DependencySpecifiers[i], - dependencySpecifier.DependencySpecifiers[i]); + dependencySpecifier.DependencySpecifiers.Should().HaveElementAt( + i, referenceDependencySpecification.DependencySpecifiers[i]); } } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs index 78882cfbe..3d9106bcc 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs @@ -4,6 +4,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Detectors.Pip; @@ -55,7 +56,7 @@ public async Task TestPipResolverSimpleGraphAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -66,7 +67,7 @@ public async Task TestPipResolverSimpleGraphAsync() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); } [TestMethod] @@ -98,7 +99,7 @@ public async Task TestPipResolverNonExistantRootAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -109,7 +110,7 @@ public async Task TestPipResolverNonExistantRootAsync() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); } [TestMethod] @@ -138,7 +139,7 @@ public async Task TestPipResolverNonExistantLeafAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -146,7 +147,7 @@ public async Task TestPipResolverNonExistantLeafAsync() expectedA.Children.Add(expectedB); expectedB.Parents.Add(expectedA); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); this.pyPiClient.Verify(x => x.FetchPackageDependenciesAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); } @@ -181,7 +182,7 @@ public async Task TestPipResolverBacktrackAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -194,7 +195,7 @@ public async Task TestPipResolverBacktrackAsync() expectedC.Parents.Add(expectedA); expectedC.Parents.Add(expectedB); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); this.pyPiClient.Verify(x => x.FetchPackageDependenciesAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(4)); } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs index 04e1158b3..e2c8e4849 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs @@ -80,53 +80,53 @@ public async Task TestPnpmDetector_SingleFileLocatesExpectedInputAsync() .WithFile("shrinkwrap1.yaml", yamlFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(5, detectedComponents.Count()); + detectedComponents.Should().HaveCount(5); var queryString = detectedComponents.Single(component => ((NpmComponent)component.Component).Name.Contains("query-string")); componentRecorder.AssertAllExplicitlyReferencedComponents( queryString.Component.Id, parentComponent => parentComponent.Name == "query-string-🙌"); - Assert.AreEqual("4.3.4", ((NpmComponent)queryString.Component).Version); - Assert.IsTrue(componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false)); + ((NpmComponent)queryString.Component).Version.Should().Be("4.3.4"); + componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false).Should().BeTrue(); var objectAssign = detectedComponents.Single(component => ((NpmComponent)component.Component).Name.Contains("object-assign")); componentRecorder.AssertAllExplicitlyReferencedComponents( objectAssign.Component.Id, parentComponent => parentComponent.Name == "query-string-🙌" && parentComponent.Version == "4.3.4"); - Assert.AreEqual("4.1.1", ((NpmComponent)objectAssign.Component).Version); - Assert.IsTrue(componentRecorder.GetEffectiveDevDependencyValue(objectAssign.Component.Id).GetValueOrDefault(false)); + ((NpmComponent)objectAssign.Component).Version.Should().Be("4.1.1"); + componentRecorder.GetEffectiveDevDependencyValue(objectAssign.Component.Id).GetValueOrDefault(false).Should().BeTrue(); var strictUriEncode = detectedComponents.Single(component => ((NpmComponent)component.Component).Name.Contains("strict-uri-encode")); componentRecorder.AssertAllExplicitlyReferencedComponents( strictUriEncode.Component.Id, parentComponent => parentComponent.Name == "query-string-🙌" && parentComponent.Version == "4.3.4"); - Assert.AreEqual("1.1.0", ((NpmComponent)strictUriEncode.Component).Version); - Assert.IsFalse(componentRecorder.GetEffectiveDevDependencyValue(strictUriEncode.Component.Id).GetValueOrDefault(true)); + ((NpmComponent)strictUriEncode.Component).Version.Should().Be("1.1.0"); + componentRecorder.GetEffectiveDevDependencyValue(strictUriEncode.Component.Id).GetValueOrDefault(true).Should().BeFalse(); var babelHelperCompilation = detectedComponents.Single(component => ((NpmComponent)component.Component).Name.Contains("helper-compilation-targets")); componentRecorder.AssertAllExplicitlyReferencedComponents( babelHelperCompilation.Component.Id, parentComponent => parentComponent.Name == "@babel/helper-compilation-targets" && parentComponent.Version == "7.10.4"); - Assert.IsFalse(componentRecorder.GetEffectiveDevDependencyValue(babelHelperCompilation.Component.Id).GetValueOrDefault(true)); + componentRecorder.GetEffectiveDevDependencyValue(babelHelperCompilation.Component.Id).GetValueOrDefault(true).Should().BeFalse(); var test = detectedComponents.Single(component => ((NpmComponent)component.Component).Name.Contains("test")); componentRecorder.AssertAllExplicitlyReferencedComponents( test.Component.Id, parentComponent => parentComponent.Name == "query-string-🙌" && parentComponent.Version == "4.3.4"); - Assert.IsTrue(componentRecorder.GetEffectiveDevDependencyValue(test.Component.Id).GetValueOrDefault(false)); + componentRecorder.GetEffectiveDevDependencyValue(test.Component.Id).GetValueOrDefault(false).Should().BeTrue(); componentRecorder.ForAllComponents(grouping => { - Assert.IsTrue(grouping.AllFileLocations.First().Contains("shrinkwrap1.yaml")); + grouping.AllFileLocations.First().Should().Contain("shrinkwrap1.yaml"); }); foreach (var component in detectedComponents) { - Assert.AreEqual(component.Component.Type, ComponentType.Npm); + ComponentType.Npm.Should().Be(component.Component.Type); } } @@ -182,13 +182,13 @@ public async Task TestPnpmDetector_SameComponentMergesRootsAndLocationsAcrossMul .WithFile("shrinkwrap2.yaml", yamlFile2) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(3, detectedComponents.Count()); + detectedComponents.Should().HaveCount(3); var strictUriEncodeComponent = detectedComponents.Select(x => new { Component = x.Component as NpmComponent, DetectedComponent = x }).FirstOrDefault(x => x.Component.Name.Contains("strict-uri-encode")); - Assert.IsNotNull(strictUriEncodeComponent); + strictUriEncodeComponent.Should().NotBeNull(); componentRecorder.AssertAllExplicitlyReferencedComponents( strictUriEncodeComponent.Component.Id, @@ -227,13 +227,13 @@ public async Task TestPnpmDetector_SpecialDependencyVersionStringDoesntBlowUsUpA .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(2, detectedComponents.Count()); + detectedComponents.Should().HaveCount(2); var msItemsViewComponent = detectedComponents.Select(x => new { Component = x.Component as NpmComponent, DetectedComponent = x }).FirstOrDefault(x => x.Component.Name.Contains("@ms/items-view")); - Assert.IsNotNull(msItemsViewComponent); + msItemsViewComponent.Should().NotBeNull(); componentRecorder.AssertAllExplicitlyReferencedComponents( msItemsViewComponent.Component.Id, parentComponent => parentComponent.Name == "query-string"); @@ -302,8 +302,8 @@ public async Task TestPnpmDetector_HandlesMalformedYamlAsync() .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -332,8 +332,8 @@ public async Task TestPnpmDetector_DependencyGraphIsCreatedAsync() .WithFile("shrinkwrap1.yaml", yamlFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(4, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(4); var queryStringComponentId = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPath("/query-string/4.3.4").Component.Id; var objectAssignComponentId = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPath("/object-assign/4.1.1").Component.Id; @@ -343,19 +343,19 @@ public async Task TestPnpmDetector_DependencyGraphIsCreatedAsync() var dependencyGraph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); var queryStringDependencies = dependencyGraph.GetDependenciesForComponent(queryStringComponentId); - Assert.AreEqual(2, queryStringDependencies.Count()); - Assert.IsTrue(queryStringDependencies.Contains(objectAssignComponentId)); - Assert.IsTrue(queryStringDependencies.Contains(testComponentId)); + queryStringDependencies.Should().HaveCount(2); + queryStringDependencies.Should().Contain(objectAssignComponentId); + queryStringDependencies.Should().Contain(testComponentId); var objectAssignDependencies = dependencyGraph.GetDependenciesForComponent(objectAssignComponentId); - Assert.AreEqual(1, objectAssignDependencies.Count()); - Assert.IsTrue(objectAssignDependencies.Contains(strictUriComponentId)); + objectAssignDependencies.Should().ContainSingle(); + objectAssignDependencies.Should().Contain(strictUriComponentId); var stringUriDependencies = dependencyGraph.GetDependenciesForComponent(strictUriComponentId); - Assert.AreEqual(0, stringUriDependencies.Count()); + stringUriDependencies.Should().BeEmpty(); var testDependencies = dependencyGraph.GetDependenciesForComponent(testComponentId); - Assert.AreEqual(0, testDependencies.Count()); + testDependencies.Should().BeEmpty(); } [TestMethod] @@ -389,10 +389,10 @@ public async Task TestPnpmDetector_DependenciesRefeToLocalPaths_DependenciesAreI var dependencyGraph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); var queryStringDependencies = dependencyGraph.GetDependenciesForComponent(queryStringComponentId); - queryStringDependencies.Should().HaveCount(1); + queryStringDependencies.Should().ContainSingle(); queryStringDependencies.Should().Contain(nthcheck); var nthCheckDependencies = dependencyGraph.GetDependenciesForComponent(nthcheck); - nthCheckDependencies.Should().HaveCount(0); + nthCheckDependencies.Should().BeEmpty(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs index 2f475d723..26a749a5f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs @@ -45,7 +45,7 @@ public async Task DeserializePnpmYamlFileAsync() parsedYaml.packages.Should().ContainKey("/@ms/items-view/0.128.9/react-dom@15.6.2+react@15.6.2"); var queryStringPackage = parsedYaml.packages["/query-string/4.3.4"]; - queryStringPackage.dependencies.Should().HaveCount(1); + queryStringPackage.dependencies.Should().ContainSingle(); queryStringPackage.dependencies.Should().ContainKey("@ms/items-view"); queryStringPackage.dependencies["@ms/items-view"].Should().BeEquivalentTo("/@ms/items-view/0.128.9/react-dom@15.6.2+react@15.6.2"); queryStringPackage.dev.Should().BeEquivalentTo("false"); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs index 67c996bc2..5e9afda14 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Detectors.CocoaPods; @@ -28,8 +29,8 @@ public async Task TestPodDetector_EmptyPodfileLockAsync() .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -64,10 +65,10 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsAsync() .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(6, detectedComponents.Count()); + detectedComponents.Should().HaveCount(6); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); @@ -106,10 +107,10 @@ public async Task TestPodDetector_DetectorRecognizeSubspecsAsSinglePodComponentA .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(2, detectedComponents.Count()); + detectedComponents.Should().HaveCount(2); this.AssertPodComponentNameAndVersion(detectedComponents, "MSAL", "1.0.7"); this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); @@ -150,10 +151,10 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsAsync() .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); this.AssertGitComponentHashAndUrl(detectedComponents, "da7223e3c455fe558de361c611df36c6dcc4229d", "https://github.com/microsoftgraph/msgraph-sdk-objc.git"); } @@ -193,10 +194,10 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); } @@ -236,10 +237,10 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); } @@ -273,10 +274,10 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromExternalPods .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(2, detectedComponents.Count()); + detectedComponents.Should().HaveCount(2); this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); this.AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); @@ -306,10 +307,10 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromLocalPathAsy .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); this.AssertPodComponentNameAndVersion(detectedComponents, "Keys", "1.0.1"); } @@ -372,10 +373,10 @@ public async Task TestPodDetector_MultiplePodfileLocksAsync() .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(8, detectedComponents.Count()); + detectedComponents.Should().HaveCount(8); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); @@ -456,10 +457,10 @@ public async Task TestPodDetector_DetectorSupportsDependencyRootsAsync() .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(8, detectedComponents.Count()); + detectedComponents.Should().HaveCount(8); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); @@ -553,10 +554,10 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots_GitUriAsync() .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(8, detectedComponents.Count()); + detectedComponents.Should().HaveCount(8); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); @@ -635,10 +636,10 @@ public async Task TestPodDetector_DetectorHandlesMainSpecRepoDifferencesAsync() .WithFile("Podfile.lock", podfileLockContent3) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); } @@ -681,10 +682,10 @@ public async Task TestPodDetector_DetectorRecognizeComponentsSpecRepoAsync() .WithFile("Podfile.lock", podfileLockContent2, fileLocation: Path.Join(Path.GetTempPath(), "sub-folder", "Podfile.lock")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); var firstComponent = detectedComponents.First(); componentRecorder.ForOneComponent(firstComponent.Component.Id, grouping => Assert.AreEqual(2, Enumerable.Count(grouping.AllFileLocations))); @@ -692,42 +693,40 @@ public async Task TestPodDetector_DetectorRecognizeComponentsSpecRepoAsync() private void AssertPodComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) { - Assert.IsNotNull( - detectedComponents.SingleOrDefault(component => + detectedComponents.SingleOrDefault(component => component.Component is PodComponent && (component.Component as PodComponent).Name.Equals(name) && - (component.Component as PodComponent).Version.Equals(version)), + (component.Component as PodComponent).Version.Equals(version)).Should().NotBeNull( $"Component with name {name} and version {version} was not found"); } private void AssertGitComponentHashAndUrl(IEnumerable detectedComponents, string commitHash, string repositoryUrl) { - Assert.IsNotNull( - detectedComponents.SingleOrDefault(component => + detectedComponents.SingleOrDefault(component => component.Component is GitComponent && (component.Component as GitComponent).CommitHash.Equals(commitHash) && - (component.Component as GitComponent).RepositoryUrl.Equals(repositoryUrl)), + (component.Component as GitComponent).RepositoryUrl.Equals(repositoryUrl)).Should().NotBeNull( $"Component with commit hash {commitHash} and repository url {repositoryUrl} was not found"); } private void AssertPodComponentHasPodComponentDependencyRoot(IComponentRecorder recorder, (string Name, string Version) component, (string Name, string Version) root) { - Assert.IsTrue(recorder.IsDependencyOfExplicitlyReferencedComponents( + recorder.IsDependencyOfExplicitlyReferencedComponents( new PodComponent(component.Name, component.Version).Id, - x => x.Id == new PodComponent(root.Name, root.Version).Id)); + x => x.Id == new PodComponent(root.Name, root.Version).Id).Should().BeTrue(); } private void AssertPodComponentHasGitComponentDependencyRoot(IComponentRecorder recorder, (string Name, string Version) component, (string Commit, string Repo) root) { - Assert.IsTrue(recorder.IsDependencyOfExplicitlyReferencedComponents( + recorder.IsDependencyOfExplicitlyReferencedComponents( new PodComponent(component.Name, component.Version).Id, - x => x.Id == new GitComponent(new Uri(root.Repo), root.Commit).Id)); + x => x.Id == new GitComponent(new Uri(root.Repo), root.Commit).Id).Should().BeTrue(); } private void AssertGitComponentHasGitComponentDependencyRoot(IComponentRecorder recorder, (string Commit, string Repo) component, (string Commit, string Repo) root) { - Assert.IsTrue(recorder.IsDependencyOfExplicitlyReferencedComponents( + recorder.IsDependencyOfExplicitlyReferencedComponents( new GitComponent(new Uri(component.Repo), component.Commit).Id, - x => x.Id == new GitComponent(new Uri(root.Repo), root.Commit).Id)); + x => x.Id == new GitComponent(new Uri(root.Repo), root.Commit).Id).Should().BeTrue(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs index 347e22f6d..36a1b8665 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs @@ -3,6 +3,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Detectors.Poetry; @@ -36,14 +37,14 @@ public async Task TestPoetryDetector_TestCustomSourceAsync() .WithFile("poetry.lock", poetryLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); this.AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); var queryString = detectedComponents.Single(component => ((PipComponent)component.Component).Name.Contains("certifi")); - Assert.IsFalse(componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false)); + componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false).Should().BeFalse(); } [TestMethod] @@ -62,15 +63,15 @@ public async Task TestPoetryDetector_TestDevDependencyAsync() .WithFile("poetry.lock", poetryLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); + detectedComponents.Should().ContainSingle(); this.AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); var queryString = detectedComponents.Single(component => ((PipComponent)component.Component).Name.Contains("certifi")); - Assert.IsTrue(componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false)); + componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false).Should().BeTrue(); } [TestMethod] @@ -113,29 +114,28 @@ public async Task TestPoetryDetector_TestGitDependencyAsync() .WithFile("poetry.lock", poetryLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(2, detectedComponents.Count()); + detectedComponents.Should().HaveCount(2); this.AssertGitComponentHashAndUrl(detectedComponents, "232a5596424c98d11c3cf2e29b2f6a6c591c2ff3", "https://github.com/requests/requests.git"); } private void AssertPipComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) { - Assert.IsNotNull( - detectedComponents.SingleOrDefault(c => + detectedComponents.SingleOrDefault(c => c.Component is PipComponent component && component.Name.Equals(name) && - component.Version.Equals(version)), + component.Version.Equals(version)).Should().NotBeNull( $"Component with name {name} and version {version} was not found"); } private void AssertGitComponentHashAndUrl(IEnumerable detectedComponents, string commitHash, string repositoryUrl) { - Assert.IsNotNull(detectedComponents.SingleOrDefault(c => + detectedComponents.SingleOrDefault(c => c.Component is GitComponent component && component.CommitHash.Equals(commitHash) && - component.RepositoryUrl.Equals(repositoryUrl))); + component.RepositoryUrl.Equals(repositoryUrl)).Should().NotBeNull(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs index 962ccb6af..234ebeb1b 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs @@ -58,7 +58,7 @@ public async Task PythonCommandService_ReturnsTrueWhenPythonExistsAsync() var service = new PythonCommandService(this.commandLineInvokationService.Object); - Assert.IsTrue(await service.PythonExistsAsync()); + (await service.PythonExistsAsync()).Should().BeTrue(); } [TestMethod] @@ -68,7 +68,7 @@ public async Task PythonCommandService_ReturnsFalseWhenPythonExistsAsync() var service = new PythonCommandService(this.commandLineInvokationService.Object); - Assert.IsFalse(await service.PythonExistsAsync()); + (await service.PythonExistsAsync()).Should().BeFalse(); } [TestMethod] @@ -78,7 +78,7 @@ public async Task PythonCommandService_ReturnsTrueWhenPythonExistsForAPathAsync( var service = new PythonCommandService(this.commandLineInvokationService.Object); - Assert.IsTrue(await service.PythonExistsAsync("test")); + (await service.PythonExistsAsync("test")).Should().BeTrue(); } [TestMethod] @@ -88,7 +88,7 @@ public async Task PythonCommandService_ReturnsFalseWhenPythonExistsForAPathAsync var service = new PythonCommandService(this.commandLineInvokationService.Object); - Assert.IsFalse(await service.PythonExistsAsync("test")); + (await service.PythonExistsAsync("test")).Should().BeFalse(); } [TestMethod] @@ -105,7 +105,7 @@ public async Task PythonCommandService_ParsesEmptySetupPyOutputCorrectlyAsync() var result = await service.ParseFileAsync(fakePath); - Assert.AreEqual(0, result.Count); + result.Should().BeEmpty(); } [TestMethod] @@ -122,7 +122,7 @@ public async Task PythonCommandService_ParsesEmptySetupPyOutputCorrectly_Python2 var result = await service.ParseFileAsync(fakePath); - Assert.AreEqual(0, result.Count); + result.Should().BeEmpty(); } [TestMethod] @@ -139,8 +139,8 @@ public async Task PythonCommandService_ParsesSetupPyOutputCorrectly_Python27None var result = await service.ParseFileAsync(fakePath); - Assert.AreEqual(1, result.Count); - Assert.AreEqual("None", result.First().PackageString); + result.Should().ContainSingle(); + result.First().PackageString.Should().Be("None"); } [TestMethod] @@ -158,11 +158,11 @@ public async Task PythonCommandService_ParsesRegularSetupPyOutputCorrectlyAsync( var result = await service.ParseFileAsync(fakePath); var expected = new string[] { "knack==0.4.1", "setuptools>=1.0,!=1.1", "vsts-cli-common==0.1.3", "vsts-cli-admin==0.1.3", "vsts-cli-build==0.1.3", "vsts-cli-code==0.1.3", "vsts-cli-team==0.1.3", "vsts-cli-package==0.1.3", "vsts-cli-work==0.1.3" }.Select(dep => (dep, null)).ToArray(); - Assert.AreEqual(9, result.Count); + result.Should().HaveCount(9); for (var i = 0; i < 9; i++) { - Assert.AreEqual(expected[i], result[i]); + result.Should().HaveElementAt(i, expected[i]); } } @@ -187,11 +187,11 @@ public async Task PythonCommandService_ParsesRequirementsTxtCorrectlyAsync() var result = await service.ParseFileAsync(testPath); var expected = new string[] { "knack==0.4.1", "vsts-cli-common==0.1.3" }.Select(dep => (dep, null)).ToArray(); - Assert.AreEqual(expected.Length, result.Count); + result.Should().HaveCount(expected.Length); for (var i = 0; i < expected.Length; i++) { - Assert.AreEqual(expected[i], result[i]); + result.Should().HaveElementAt(i, expected[i]); } } finally @@ -223,8 +223,8 @@ public async Task ParseFile_RequirementTxtHasComment_CommentAreIgnoredAsync() var result = await service.ParseFileAsync(testPath); (string, GitComponent) expected = ("knack==0.4.1", null); - Assert.AreEqual(1, result.Count); - Assert.AreEqual(expected, result.First()); + result.Should().ContainSingle(); + result.First().Should().Be(expected); } finally { @@ -240,7 +240,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentsSupportedAsync { await this.SetupAndParseReqsTxtAsync(this.requirementstxtBasicGitComponent, parseResult => { - parseResult.Count.Should().Be(1); + parseResult.Should().ContainSingle(); var (packageString, component) = parseResult.Single(); packageString.Should().BeNull(); @@ -257,7 +257,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentAndEnvironmentM { await this.SetupAndParseReqsTxtAsync(this.requirementstxtGitComponentAndEnvironmentMarker, parseResult => { - parseResult.Count.Should().Be(1); + parseResult.Should().ContainSingle(); var (packageString, component) = parseResult.Single(); packageString.Should().BeNull(); @@ -274,7 +274,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentAndCommentAsync { await this.SetupAndParseReqsTxtAsync(this.requirementstxtGitComponentAndComment, parseResult => { - parseResult.Count.Should().Be(1); + parseResult.Should().ContainSingle(); var (packageString, component) = parseResult.Single(); packageString.Should().BeNull(); @@ -291,7 +291,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentAndCommentAndEn { await this.SetupAndParseReqsTxtAsync(this.requirementstxtGitComponentAndCommentAndEnvironmentMarker, parseResult => { - parseResult.Count.Should().Be(1); + parseResult.Should().ContainSingle(); var (packageString, component) = parseResult.Single(); packageString.Should().BeNull(); @@ -308,7 +308,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenG { await this.SetupAndParseReqsTxtAsync(this.requirementstxtGitComponentBranchInsteadOfCommitId, parseResult => { - parseResult.Count.Should().Be(0); + parseResult.Should().BeEmpty(); }); } @@ -317,7 +317,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenG { await this.SetupAndParseReqsTxtAsync(this.requirementstxtGitComponentReleaseInsteadOfCommitId, parseResult => { - parseResult.Count.Should().Be(0); + parseResult.Should().BeEmpty(); }); } @@ -326,7 +326,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenG { await this.SetupAndParseReqsTxtAsync(this.requirementstxtGitComponentCommitIdWrongLength, parseResult => { - parseResult.Count.Should().Be(0); + parseResult.Should().BeEmpty(); }); } @@ -335,7 +335,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentsMultipleAsync( { await this.SetupAndParseReqsTxtAsync(this.requirementstxtDoubleGitComponents, parseResult => { - parseResult.Count.Should().Be(2); + parseResult.Should().HaveCount(2); var (packageString, component) = parseResult.First(); packageString.Should().BeNull(); @@ -360,7 +360,7 @@ public async Task ParseFile_RequirementTxtHasComment_GitComponentWrappedInRegula { await this.SetupAndParseReqsTxtAsync(this.requirementstxtGitComponentWrappedinRegularComponents, parseResult => { - parseResult.Count.Should().Be(3); + parseResult.Should().HaveCount(3); var (packageString, component) = parseResult.First(); packageString.Should().NotBeNull(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs index 6c557ca77..4a436e7b5 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs @@ -17,12 +17,12 @@ public void TestBasicVersionConstruction() { var pythonVersion = PythonVersion.Create("4!3.2.1.1rc2.post99.dev2"); - Assert.AreEqual(4, pythonVersion.Epoch); - Assert.AreEqual("3.2.1.1", pythonVersion.Release); - Assert.AreEqual("rc", pythonVersion.PreReleaseLabel); - Assert.AreEqual(99, pythonVersion.PostNumber); - Assert.AreEqual("dev", pythonVersion.DevLabel); - Assert.AreEqual(2, pythonVersion.DevNumber); + pythonVersion.Epoch.Should().Be(4); + pythonVersion.Release.Should().Be("3.2.1.1"); + pythonVersion.PreReleaseLabel.Should().Be("rc"); + pythonVersion.PostNumber.Should().Be(99); + pythonVersion.DevLabel.Should().Be("dev"); + pythonVersion.DevNumber.Should().Be(2); } [TestMethod] @@ -30,13 +30,13 @@ public void TestDefaultDevVersionConstruction() { var pythonVersion = PythonVersion.Create("4!3.2.1.1rc2.post90.dev"); - Assert.AreEqual(4, pythonVersion.Epoch); - Assert.AreEqual("3.2.1.1", pythonVersion.Release); - Assert.AreEqual("rc", pythonVersion.PreReleaseLabel); - Assert.AreEqual(2, pythonVersion.PreReleaseNumber); - Assert.AreEqual(90, pythonVersion.PostNumber); - Assert.AreEqual("dev", pythonVersion.DevLabel); - Assert.AreEqual(0, pythonVersion.DevNumber); + pythonVersion.Epoch.Should().Be(4); + pythonVersion.Release.Should().Be("3.2.1.1"); + pythonVersion.PreReleaseLabel.Should().Be("rc"); + pythonVersion.PreReleaseNumber.Should().Be(2); + pythonVersion.PostNumber.Should().Be(90); + pythonVersion.DevLabel.Should().Be("dev"); + pythonVersion.DevNumber.Should().Be(0); } [TestMethod] @@ -96,8 +96,8 @@ public void TestVersionValidForSpec() foreach (var (specs, validVersions, invalidVersions) in testCases) { - Assert.IsTrue(validVersions.All(x => PythonVersionUtilities.VersionValidForSpec(x, specs))); - Assert.IsTrue(invalidVersions.All(x => !PythonVersionUtilities.VersionValidForSpec(x, specs))); + validVersions.Should().OnlyContain(x => PythonVersionUtilities.VersionValidForSpec(x, specs)); + invalidVersions.Should().OnlyContain(x => !PythonVersionUtilities.VersionValidForSpec(x, specs)); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs index 1858c14e5..37bfce528 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs @@ -70,10 +70,10 @@ BUNDLED WITH .WithFile("2Gemfile.lock", gemFileLockContent2) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(7, detectedComponents.Count()); + detectedComponents.Should().HaveCount(7); this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); @@ -99,10 +99,10 @@ BUNDLED WITH .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(2, detectedComponents.Count()); + detectedComponents.Should().HaveCount(2); // we do not record invalid/unknown versions this.AssertRubyComponentNameAndVersion(detectedComponents, "CFPropertyList", "3.0.4"); @@ -132,10 +132,10 @@ BUNDLED WITH .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(6, detectedComponents.Count()); + detectedComponents.Should().HaveCount(6); this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); @@ -166,10 +166,10 @@ public async Task TestRubyDetector_DetectorRecognizeGemComponentsAsync() .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(5, detectedComponents.Count()); + detectedComponents.Should().HaveCount(5); this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); @@ -196,10 +196,10 @@ public async Task TestRubyDetector_ParentWithTildeInVersion_IsExcludedAsync() .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(3, detectedComponents.Count()); + detectedComponents.Should().HaveCount(3); this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); @@ -249,20 +249,20 @@ public async Task TestRubyDetector_DetectorCreatesADependencyGraphAsync() acmeClientDependencies.Should().Contain(dep => dep == actioncableComponentId); var actionCableDependencies = dependencyGraph.GetDependenciesForComponent(actioncableComponentId); - actionCableDependencies.Should().HaveCount(1); + actionCableDependencies.Should().ContainSingle(); actionCableDependencies.Should().Contain(dep => dep == nior4rComponentId); var faradayDependencies = dependencyGraph.GetDependenciesForComponent(faradayComponentId); - faradayDependencies.Should().HaveCount(0); + faradayDependencies.Should().BeEmpty(); var niorDependencies = dependencyGraph.GetDependenciesForComponent(nior4rComponentId); - niorDependencies.Should().HaveCount(0); + niorDependencies.Should().BeEmpty(); var websocketDependencies = dependencyGraph.GetDependenciesForComponent(websocketDriverComponentId); - websocketDependencies.Should().HaveCount(0); + websocketDependencies.Should().BeEmpty(); var mailComponentDependencies = dependencyGraph.GetDependenciesForComponent(mailComponentId); - mailComponentDependencies.Should().HaveCount(1); + mailComponentDependencies.Should().ContainSingle(); mailComponentDependencies.Should().Contain(dep => dep == websocketDriverComponentId); } @@ -341,7 +341,7 @@ public async Task TestRubyDetector_DetectorRecognizeGitComponentsAsync() .ExecuteDetectorAsync(); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(3, detectedComponents.Count()); + detectedComponents.Should().HaveCount(3); this.AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-1", repositoryUrl: "https://github.com/test/abc.git"); this.AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-2", repositoryUrl: "https://github.com/mikel/mail.git"); this.AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); @@ -395,7 +395,7 @@ public async Task TestRubyDetector_DetectorRecognizeLocalDependenciesAsync() .ExecuteDetectorAsync(); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(3, detectedComponents.Count()); + detectedComponents.Should().HaveCount(3); this.AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); this.AssertRubyComponentNameAndVersion(detectedComponents, name: "test", version: "1.0.0"); @@ -404,27 +404,26 @@ public async Task TestRubyDetector_DetectorRecognizeLocalDependenciesAsync() private void AssertRubyComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) { - Assert.IsNotNull( - detectedComponents.SingleOrDefault(c => + detectedComponents.SingleOrDefault(c => c.Component is RubyGemsComponent component && component.Name.Equals(name) && - component.Version.Equals(version)), + component.Version.Equals(version)).Should().NotBeNull( $"Component with name {name} and version {version} was not found"); } private void AssertGitComponentHashAndUrl(IEnumerable detectedComponents, string commitHash, string repositoryUrl) { - Assert.IsNotNull(detectedComponents.SingleOrDefault(c => + detectedComponents.SingleOrDefault(c => c.Component is GitComponent component && component.CommitHash.Equals(commitHash) && - component.RepositoryUrl.Equals(repositoryUrl))); + component.RepositoryUrl.Equals(repositoryUrl)).Should().NotBeNull(); } private void AssertGitComponentAsRootAndGitComponentAsSubDependency(IComponentRecorder recorder, string rootHash, string subDependencyHash) { var childDep = recorder.GetDetectedComponents().First(x => (x.Component as GitComponent)?.CommitHash == subDependencyHash); - Assert.IsTrue(recorder.IsDependencyOfExplicitlyReferencedComponents( + recorder.IsDependencyOfExplicitlyReferencedComponents( childDep.Component.Id, - parent => parent.CommitHash == rootHash)); + parent => parent.CommitHash == rootHash).Should().BeTrue(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs index ea5403a1d..1339f1ef2 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs @@ -237,8 +237,8 @@ public async Task TestGraphIsCorrectAsync() .WithFile("Cargo.lock", this.testCargoLockString) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(6, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(6); var graph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); // There should only be 1 @@ -288,11 +288,11 @@ public async Task TestSupportsCargoV1AndV2DefinitionPairsAsync() .WithScanRequest(request) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); - componentGraphs.Count.Should().Be(2); // 1 for each detector + componentGraphs.Should().HaveCount(2); // 1 for each detector } [TestMethod] @@ -303,11 +303,11 @@ public async Task TestSupportsMultipleCargoV1DefinitionPairsAsync() .WithFile("Cargo.lock", this.testCargoLockString, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); - componentGraphs.Count.Should().Be(2); // 1 graph for each Cargo.lock + componentGraphs.Should().HaveCount(2); // 1 graph for each Cargo.lock var graph1 = componentGraphs.Values.First(); var graph2 = componentGraphs.Values.Skip(1).First(); @@ -326,11 +326,11 @@ public async Task TestSupportsMultipleCargoV2DefinitionPairsAsync() .WithFile("Cargo.lock", this.testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); - componentGraphs.Count.Should().Be(2); // 1 graph for each Cargo.lock + componentGraphs.Should().HaveCount(2); // 1 graph for each Cargo.lock var graph1 = componentGraphs.Values.First(); var graph2 = componentGraphs.Values.Skip(1).First(); @@ -348,8 +348,8 @@ public async Task TestRustDetectorAsync() .WithFile("Cargo.lock", this.testCargoLockString) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(6, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(6); IDictionary packageVersions = new Dictionary() { @@ -378,7 +378,7 @@ public async Task TestRustDetectorAsync() var packageName = (discoveredComponent.Component as CargoComponent).Name; // Verify version - Assert.AreEqual(packageVersions[packageName], (discoveredComponent.Component as CargoComponent).Version); + (discoveredComponent.Component as CargoComponent).Version.Should().Be(packageVersions[packageName]); var dependencyRoots = new HashSet(); @@ -393,7 +393,7 @@ public async Task TestRustDetectorAsync() // Verify all packages were detected foreach (var expectedPackage in packageVersions.Keys) { - Assert.IsTrue(componentNames.Contains(expectedPackage)); + componentNames.Should().Contain(expectedPackage); } } @@ -404,8 +404,8 @@ public async Task TestRustV2DetectorAsync() .WithFile("Cargo.lock", this.testCargoLockV2String) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(7, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(7); var packageVersions = new List() { @@ -436,7 +436,7 @@ public async Task TestRustV2DetectorAsync() var componentKey = $"{component.Name} {component.Version}"; // Verify version - Assert.IsTrue(packageVersions.Contains(componentKey)); + packageVersions.Should().Contain(componentKey); componentRecorder.AssertAllExplicitlyReferencedComponents( discoveredComponent.Component.Id, @@ -449,7 +449,7 @@ public async Task TestRustV2DetectorAsync() // Verify all packages were detected foreach (var expectedPackage in packageVersions) { - Assert.IsTrue(componentNames.Contains(expectedPackage)); + componentNames.Should().Contain(expectedPackage); } } @@ -529,8 +529,8 @@ public async Task TestRustV2Detector_DuplicatePackageAsync() .WithFile("Cargo.lock", testCargoLock) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(7, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(7); var graph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); // There should only be 1 @@ -598,11 +598,11 @@ public async Task TestRustDetector_SupportEmptySourceAsync() result.ResultCode.Should().Be(ProcessingResultCode.Success); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); - dependencyGraphs.Count.Should().Be(1); + dependencyGraphs.Should().ContainSingle(); var dependencyGraph = dependencyGraphs.Single().Value; var foundComponents = dependencyGraph.GetComponents(); - foundComponents.Count().Should().Be(2); + foundComponents.Should().HaveCount(2); componentRecorder.ForOneComponent("other_dependency_dependency 0.1.12-alpha.6 - Cargo", (grouping) => { @@ -628,8 +628,8 @@ private async Task TestRustDetector_WorkspacesWithTopLevelDependenciesAsync(stri .WithFile("Cargo.lock", string.Concat(this.testWorkspaceLockBaseDependency, lockFile)) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(7, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(7); var packageVersions = new List() { @@ -660,7 +660,7 @@ private async Task TestRustDetector_WorkspacesWithTopLevelDependenciesAsync(stri var componentKey = $"{component.Name} {component.Version}"; // Verify version - Assert.IsTrue(packageVersions.Contains(componentKey)); + packageVersions.Should().Contain(componentKey); componentRecorder.AssertAllExplicitlyReferencedComponents( discoveredComponent.Component.Id, @@ -673,7 +673,7 @@ private async Task TestRustDetector_WorkspacesWithTopLevelDependenciesAsync(stri // Verify all packages were detected foreach (var expectedPackage in packageVersions) { - Assert.IsTrue(componentNames.Contains(expectedPackage)); + componentNames.Should().Contain(expectedPackage); } } @@ -695,8 +695,8 @@ private async Task TestRustDetector_WorkspacesNoTopLevelDependenciesAsync(string .WithFile("Cargo.lock", lockFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(6, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(6); } [TestMethod] @@ -719,10 +719,10 @@ private async Task TestRustDetector_WorkspacesWithSubDirectoriesAsync(string loc var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(6, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(6); - Assert.AreEqual(1, componentGraphs.Count); // Only 1 Cargo.lock is specified + componentGraphs.Should().ContainSingle(); // Only 1 Cargo.lock is specified // A root Cargo.lock componentRecorder.ForAllComponents(x => x.AllFileLocations.Count().Should().Be(1)); @@ -758,8 +758,8 @@ public async Task TestRustDetector_UnequalButSemverCompatibleRootAsync() .WithFile("Cargo.lock", testLockString) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(2, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(2); var graph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); // There should only be 1 @@ -796,11 +796,11 @@ public async Task TestRustDetector_GitDependencyAsync() .WithFile("Cargo.lock", testLockString) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(1); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); - dependencyGraphs.Count.Should().Be(1); + dependencyGraphs.Should().ContainSingle(); var dependencyGraph = dependencyGraphs.Single().Value; dependencyGraph.Contains("my_git_dep 0.1.0 - Cargo").Should().BeTrue(); @@ -832,13 +832,13 @@ public async Task TestRustDetector_MultipleRegistriesAsync() .WithFile("Cargo.lock", testLockString) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); // If registries have identity, this should be 2 - Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count()); + componentRecorder.GetDetectedComponents().Count().Should().Be(1); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); - dependencyGraphs.Count.Should().Be(1); + dependencyGraphs.Should().ContainSingle(); var dependencyGraph = dependencyGraphs.Single().Value; @@ -874,8 +874,8 @@ public async Task TestRustV2Detector_StdWorkspaceDependencyAsync() .WithFile("Cargo.lock", testCargoLock) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(1); var graph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); // There should only be 1 diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs index 79336bdbb..164e32a3e 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs @@ -7,6 +7,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Common.DependencyGraph; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; @@ -104,7 +105,7 @@ public async Task TestSbomDetector_SimpleSbomAsync() .WithFile(spdxFileName, spdxFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); var components = detectedComponents.ToList(); @@ -119,13 +120,13 @@ public async Task TestSbomDetector_SimpleSbomAsync() var checksum = BitConverter.ToString(SHA1.HashData(Encoding.UTF8.GetBytes(spdxFile))).Replace("-", string.Empty).ToLower(); #pragma warning restore CA5350 - Assert.AreEqual(1, components.Count); - Assert.AreEqual(sbomComponent.Name, "Test 1.0.0"); - Assert.AreEqual(sbomComponent.RootElementId, "SPDXRef-RootPackage"); - Assert.AreEqual(sbomComponent.DocumentNamespace, new Uri("https://sbom.microsoft/Test/1.0.0/61de1a5-57cc-4732-9af5-edb321b4a7ee")); - Assert.AreEqual(sbomComponent.SpdxVersion, "SPDX-2.2"); - Assert.AreEqual(sbomComponent.Checksum, checksum); - Assert.AreEqual(sbomComponent.Path, Path.Combine(Path.GetTempPath(), spdxFileName)); + components.Should().ContainSingle(); + sbomComponent.Name.Should().Be("Test 1.0.0"); + sbomComponent.RootElementId.Should().Be("SPDXRef-RootPackage"); + sbomComponent.DocumentNamespace.Should().Be(new Uri("https://sbom.microsoft/Test/1.0.0/61de1a5-57cc-4732-9af5-edb321b4a7ee")); + sbomComponent.SpdxVersion.Should().Be("SPDX-2.2"); + sbomComponent.Checksum.Should().Be(checksum); + sbomComponent.Path.Should().Be(Path.Combine(Path.GetTempPath(), spdxFileName)); } [TestMethod] @@ -137,11 +138,11 @@ public async Task TestSbomDetector_BlankJsonAsync() .WithFile("manifest.spdx.json", spdxFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); var components = detectedComponents.ToList(); - Assert.IsFalse(components.Any()); + components.Should().BeEmpty(); } [TestMethod] @@ -153,10 +154,10 @@ public async Task TestSbomDetector_InvalidFileAsync() .WithFile("manifest.spdx.json", spdxFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); var components = detectedComponents.ToList(); - Assert.IsFalse(components.Any()); + components.Should().BeEmpty(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePipComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePipComponentDetectorTests.cs index 7068f4154..d0512cb7a 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePipComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePipComponentDetectorTests.cs @@ -53,7 +53,7 @@ public async Task TestPipDetector_PythonNotInstalledAsync() .WithFile("setup.py", string.Empty) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); this.mockLogger.VerifyAll(); } @@ -62,7 +62,7 @@ public async Task TestPipDetector_PythonInstalledNoFilesAsync() { var (result, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); } [TestMethod] @@ -101,23 +101,23 @@ public async Task TestPipDetector_SetupPyAndRequirementsTxtAsync() .WithFile("requirements.txt", string.Empty) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); + result.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(8, detectedComponents.Count()); + detectedComponents.Should().HaveCount(8); var pipComponents = detectedComponents.Where(detectedComponent => detectedComponent.Component.Id.Contains("pip")).ToList(); - Assert.AreEqual("1.2.3", ((PipComponent)pipComponents.Single(x => ((PipComponent)x.Component).Name == "z").Component).Version); + ((PipComponent)pipComponents.Single(x => ((PipComponent)x.Component).Name == "z").Component).Version.Should().Be("1.2.3"); foreach (var item in setupPyRoots) { var reference = item.Value; - Assert.AreEqual(reference.Version, ((PipComponent)pipComponents.Single(x => ((PipComponent)x.Component).Name == reference.Name).Component).Version); + ((PipComponent)pipComponents.Single(x => ((PipComponent)x.Component).Name == reference.Name).Component).Version.Should().Be(reference.Version); } var gitComponents = detectedComponents.Where(detectedComponent => detectedComponent.Component.Type == ComponentType.Git); - gitComponents.Count().Should().Be(1); + gitComponents.Should().ContainSingle(); var gitComponent = (GitComponent)gitComponents.Single().Component; gitComponent.RepositoryUrl.Should().Be("https://github.com/example/example"); @@ -157,8 +157,8 @@ public async Task TestPipDetector_ComponentsDedupedAcrossFilesAsync() .WithFile("requirements.txt", string.Empty, fileLocation: Path.Join(Path.GetTempPath(), "TEST", "requirements.txt")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(5, componentRecorder.GetDetectedComponents().Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(5); } [TestMethod] @@ -212,8 +212,8 @@ public async Task TestPipDetector_ComponentRecorderAsync() var discoveredComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - Assert.AreEqual(11, discoveredComponents.Count()); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + discoveredComponents.Should().HaveCount(11); var rootIds = new[] { @@ -239,7 +239,7 @@ public async Task TestPipDetector_ComponentRecorderAsync() this.CheckChild(componentRecorder, "dog 2.1 - pip", new[] { "c 1.0 - pip", }); var graphsByLocations = componentRecorder.GetDependencyGraphsByLocation(); - Assert.AreEqual(2, graphsByLocations.Count); + graphsByLocations.Should().HaveCount(2); var graph1ComponentsWithDeps = new Dictionary { @@ -252,8 +252,8 @@ public async Task TestPipDetector_ComponentRecorderAsync() }; var graph1 = graphsByLocations[file1]; - Assert.IsTrue(graph1ComponentsWithDeps.Keys.Take(2).All(graph1.IsComponentExplicitlyReferenced)); - Assert.IsTrue(graph1ComponentsWithDeps.Keys.Skip(2).All(a => !graph1.IsComponentExplicitlyReferenced(a))); + graph1ComponentsWithDeps.Keys.Take(2).All(graph1.IsComponentExplicitlyReferenced).Should().BeTrue(); + graph1ComponentsWithDeps.Keys.Skip(2).Should().OnlyContain(a => !graph1.IsComponentExplicitlyReferenced(a)); this.CheckGraphStructure(graph1, graph1ComponentsWithDeps); var graph2ComponentsWithDeps = new Dictionary @@ -269,38 +269,33 @@ public async Task TestPipDetector_ComponentRecorderAsync() }; var graph2 = graphsByLocations[file2]; - Assert.IsTrue(graph2ComponentsWithDeps.Keys.Take(3).All(graph2.IsComponentExplicitlyReferenced)); - Assert.IsTrue(graph2ComponentsWithDeps.Keys.Skip(3).All(a => !graph2.IsComponentExplicitlyReferenced(a))); + graph2ComponentsWithDeps.Keys.Take(3).All(graph2.IsComponentExplicitlyReferenced).Should().BeTrue(); + graph2ComponentsWithDeps.Keys.Skip(3).Should().OnlyContain(a => !graph2.IsComponentExplicitlyReferenced(a)); this.CheckGraphStructure(graph2, graph2ComponentsWithDeps); } private void CheckGraphStructure(IDependencyGraph graph, Dictionary graphComponentsWithDeps) { var graphComponents = graph.GetComponents().ToArray(); - Assert.AreEqual( + graphComponents.Should().HaveCount( graphComponentsWithDeps.Keys.Count, - graphComponents.Length, $"Expected {graphComponentsWithDeps.Keys.Count} component to be recorded but got {graphComponents.Length} instead!"); foreach (var componentId in graphComponentsWithDeps.Keys) { - Assert.IsTrue( - graphComponents.Contains(componentId), - $"Component `{componentId}` not recorded!"); + graphComponents.Should().Contain(componentId, $"Component `{componentId}` not recorded!"); var recordedDeps = graph.GetDependenciesForComponent(componentId).ToArray(); var expectedDeps = graphComponentsWithDeps[componentId]; - Assert.AreEqual( + recordedDeps.Should().HaveCount( expectedDeps.Length, - recordedDeps.Length, $"Count missmatch of expected dependencies ({JsonConvert.SerializeObject(expectedDeps)}) and recorded dependencies ({JsonConvert.SerializeObject(recordedDeps)}) for `{componentId}`!"); foreach (var expectedDep in expectedDeps) { - Assert.IsTrue( - recordedDeps.Contains(expectedDep), - $"Expected `{expectedDep}` in the list of dependencies for `{componentId}` but only recorded: {JsonConvert.SerializeObject(recordedDeps)}"); + recordedDeps.Should().Contain( + expectedDep, $"Expected `{expectedDep}` in the list of dependencies for `{componentId}` but only recorded: {JsonConvert.SerializeObject(recordedDeps)}"); } } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePythonResolverTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePythonResolverTests.cs index 44e07590e..20c39ff5a 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePythonResolverTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePythonResolverTests.cs @@ -7,6 +7,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Linq; using System.Text; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Detectors.Pip; @@ -58,7 +59,7 @@ public async Task TestPipResolverSimpleGraphAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -69,7 +70,7 @@ public async Task TestPipResolverSimpleGraphAsync() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); } [TestMethod] @@ -104,7 +105,7 @@ public async Task TestPipResolverNonExistantRootAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -115,7 +116,7 @@ public async Task TestPipResolverNonExistantRootAsync() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); } [TestMethod] @@ -145,7 +146,7 @@ public async Task TestPipResolverNonExistantLeafAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -153,7 +154,7 @@ public async Task TestPipResolverNonExistantLeafAsync() expectedA.Children.Add(expectedB); expectedB.Parents.Add(expectedA); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); this.simplePyPiClient.Verify(x => x.FetchPackageFileStreamAsync(It.IsAny()), Times.Exactly(2)); } @@ -189,7 +190,7 @@ public async Task TestPipResolverBacktrackAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -202,7 +203,7 @@ public async Task TestPipResolverBacktrackAsync() expectedC.Parents.Add(expectedA); expectedC.Parents.Add(expectedB); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); this.simplePyPiClient.Verify(x => x.FetchPackageFileStreamAsync(It.IsAny()), Times.Exactly(4)); } @@ -235,7 +236,7 @@ public async Task TestPipResolverVersionExtractionWithDifferentVersionFormatsAsy var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.15.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.19")); @@ -246,7 +247,7 @@ public async Task TestPipResolverVersionExtractionWithDifferentVersionFormatsAsy expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); } [TestMethod] @@ -278,7 +279,7 @@ public async Task TestPipResolverVersionExtractionWithDifferentPackageTypesAsync var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "1.20")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0.0")); @@ -286,7 +287,7 @@ public async Task TestPipResolverVersionExtractionWithDifferentPackageTypesAsync expectedA.Children.Add(expectedB); expectedB.Parents.Add(expectedA); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); } [TestMethod] @@ -344,7 +345,7 @@ public async Task TestPipResolverVersionExtractionWithUnconventionalVersionsAsyn var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); } [TestMethod] @@ -377,7 +378,7 @@ public async Task TestPipResolverWithMultipleReleasesAsync() var resolveResult = await resolver.ResolveRootsAsync(this.recorderMock.Object, dependencies); - Assert.IsNotNull(resolveResult); + resolveResult.Should().NotBeNull(); var expectedA = new PipGraphNode(new PipComponent("a", "10.0.0")); var expectedB = new PipGraphNode(new PipComponent("b", "1.0")); @@ -388,7 +389,7 @@ public async Task TestPipResolverWithMultipleReleasesAsync() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.CompareGraphs(resolveResult.First(), expectedA).Should().BeTrue(); } private bool CompareGraphs(PipGraphNode a, PipGraphNode b) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs index a805dc00e..8659fed92 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs @@ -4,6 +4,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.IO; using System.Linq; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Common.DependencyGraph; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.TypedComponent; @@ -66,7 +67,7 @@ public async Task TestNlohmannAsync() .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); var components = detectedComponents.ToList(); @@ -77,13 +78,13 @@ public async Task TestNlohmannAsync() throw new AssertFailedException($"{nameof(sbomComponent)} is null"); } - Assert.AreEqual(1, components.Count); - Assert.AreEqual("nlohmann-json", sbomComponent.Name); - Assert.AreEqual("3.10.4", sbomComponent.Version); - Assert.AreEqual(5, sbomComponent.PortVersion); - Assert.AreEqual("SPDXRef-port", sbomComponent.SPDXID); - Assert.AreEqual("git+https://github.com/Microsoft/vcpkg#ports/nlohmann-json", sbomComponent.DownloadLocation); - Assert.AreEqual("pkg:vcpkg/nlohmann-json@3.10.4?port_version=5", sbomComponent.PackageUrl.ToString()); + components.Should().ContainSingle(); + sbomComponent.Name.Should().Be("nlohmann-json"); + sbomComponent.Version.Should().Be("3.10.4"); + sbomComponent.PortVersion.Should().Be(5); + sbomComponent.SPDXID.Should().Be("SPDXRef-port"); + sbomComponent.DownloadLocation.Should().Be("git+https://github.com/Microsoft/vcpkg#ports/nlohmann-json"); + sbomComponent.PackageUrl.ToString().Should().Be("pkg:vcpkg/nlohmann-json@3.10.4?port_version=5"); } [TestMethod] @@ -125,24 +126,24 @@ public async Task TestTinyxmlAndResourceAsync() .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); var components = detectedComponents.ToList(); - Assert.AreEqual(2, components.Count); + components.Should().HaveCount(2); var sbomComponent = (VcpkgComponent)components.FirstOrDefault(c => ((VcpkgComponent)c?.Component).SPDXID.Equals("SPDXRef-binary")).Component; - Assert.IsNotNull(sbomComponent); - Assert.AreEqual("tinyxml2:x64-linux", sbomComponent.Name); - Assert.AreEqual("5c7679507def92c5c71df44aec08a90a5c749f7f805b3f0e8e70f5e8a5b1b8d0", sbomComponent.Version); - Assert.AreEqual("SPDXRef-binary", sbomComponent.SPDXID); - Assert.AreEqual("NONE", sbomComponent.DownloadLocation); + sbomComponent.Should().NotBeNull(); + sbomComponent.Name.Should().Be("tinyxml2:x64-linux"); + sbomComponent.Version.Should().Be("5c7679507def92c5c71df44aec08a90a5c749f7f805b3f0e8e70f5e8a5b1b8d0"); + sbomComponent.SPDXID.Should().Be("SPDXRef-binary"); + sbomComponent.DownloadLocation.Should().Be("NONE"); sbomComponent = (VcpkgComponent)components.FirstOrDefault(c => ((VcpkgComponent)c.Component).SPDXID.Equals("SPDXRef-resource-1")).Component; - Assert.AreEqual("leethomason/tinyxml2", sbomComponent.Name); - Assert.AreEqual("9.0.0", sbomComponent.Version); - Assert.AreEqual("SPDXRef-resource-1", sbomComponent.SPDXID); - Assert.AreEqual("git+https://github.com/leethomason/tinyxml2", sbomComponent.DownloadLocation); + sbomComponent.Name.Should().Be("leethomason/tinyxml2"); + sbomComponent.Version.Should().Be("9.0.0"); + sbomComponent.SPDXID.Should().Be("SPDXRef-resource-1"); + sbomComponent.DownloadLocation.Should().Be("git+https://github.com/leethomason/tinyxml2"); } [TestMethod] @@ -154,11 +155,11 @@ public async Task TestBlankJsonAsync() .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); var components = detectedComponents.ToList(); - Assert.IsFalse(components.Any()); + components.Should().BeEmpty(); } [TestMethod] @@ -170,10 +171,10 @@ public async Task TestInvalidFileAsync() .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); var components = detectedComponents.ToList(); - Assert.IsFalse(components.Any()); + components.Should().BeEmpty(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnBlockFileTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnBlockFileTests.cs index a116883ca..8cdfb0096 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnBlockFileTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnBlockFileTests.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; +using FluentAssertions; using Microsoft.ComponentDetection.Detectors.Yarn; using Microsoft.ComponentDetection.Detectors.Yarn.Parsers; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -42,9 +43,9 @@ public async Task BlockFileParserWithEmptyStream_ProducesEnumerableOfZeroAsync() file = await YarnBlockFile.CreateBlockFileAsync(stream); } - Assert.AreEqual(0, file.Count()); - Assert.AreEqual(string.Empty, file.VersionHeader); - Assert.AreEqual(YarnLockVersion.Invalid, file.YarnLockVersion); + file.Should().BeEmpty(); + file.VersionHeader.Should().Be(string.Empty); + file.YarnLockVersion.Should().Be(YarnLockVersion.Invalid); } [TestMethod] @@ -62,9 +63,9 @@ public async Task BlockFileParserV1WithVersionString_ProducesEnumerableOfZeroAsy var file = await YarnBlockFile.CreateBlockFileAsync(stream); - Assert.AreEqual(0, file.Count()); - Assert.AreEqual(yarnLockFileVersionString, file.VersionHeader); - Assert.AreEqual(YarnLockVersion.V1, file.YarnLockVersion); + file.Should().BeEmpty(); + file.VersionHeader.Should().Be(yarnLockFileVersionString); + file.YarnLockVersion.Should().Be(YarnLockVersion.V1); } [TestMethod] @@ -90,12 +91,14 @@ public async Task BlockFileParserV1WithSingleBlock_ParsesAsync() var block = file.Single(); - Assert.AreEqual(block.Title, "block1"); - Assert.AreEqual(1, block.Children.Count); - Assert.AreEqual("value", block.Values["property"]); - Assert.AreEqual("otherValue", block.Children.Single(x => x.Title == "block2").Values["otherProperty"]); - Assert.AreEqual(yarnLockFileVersionString, file.VersionHeader); - Assert.AreEqual(YarnLockVersion.V1, file.YarnLockVersion); + block.Title.Should().Be("block1"); + block.Children.Should().ContainSingle(); + block.Values["property"].Should().Be("value"); + block.Children.Single(x => x.Title == "block2").Values.Should().ContainKey("otherProperty"); + var value = block.Children.Single(x => x.Title == "block2").Values["otherProperty"]; + value.Should().Be("otherValue"); + file.VersionHeader.Should().Be(yarnLockFileVersionString); + file.YarnLockVersion.Should().Be(YarnLockVersion.V1); } [TestMethod] @@ -137,9 +140,9 @@ public async Task BlockFileParserV1WithSeveralBlocks_ParsesAsync() var file = await YarnBlockFile.CreateBlockFileAsync(stream); - Assert.AreEqual(3, file.Count()); - Assert.AreEqual(yarnLockFileVersionString, file.VersionHeader); - Assert.AreEqual(YarnLockVersion.V1, file.YarnLockVersion); + file.Should().HaveCount(3); + file.VersionHeader.Should().Be(yarnLockFileVersionString); + file.YarnLockVersion.Should().Be(YarnLockVersion.V1); } [TestMethod] @@ -164,9 +167,9 @@ public async Task BlockFileParserV2WithMetadataBlock_ParsesAsync() var file = await YarnBlockFile.CreateBlockFileAsync(stream); - Assert.AreEqual(0, file.Count()); - Assert.AreEqual(yarnLockFileVersionString, file.VersionHeader); - Assert.AreEqual(YarnLockVersion.V2, file.YarnLockVersion); + file.Should().BeEmpty(); + file.VersionHeader.Should().Be(yarnLockFileVersionString); + file.YarnLockVersion.Should().Be(YarnLockVersion.V2); } [TestMethod] @@ -199,12 +202,13 @@ public async Task BlockFileParserV2WithSingleBlock_ParsesAsync() var block = file.Single(); - Assert.AreEqual(block.Title, "block1"); - Assert.AreEqual(1, block.Children.Count); - Assert.AreEqual("value", block.Values["property"]); - Assert.AreEqual("otherValue", block.Children.Single(x => x.Title == "block2").Values["otherProperty"]); - Assert.AreEqual(yarnLockFileVersionString, file.VersionHeader); - Assert.AreEqual(YarnLockVersion.V2, file.YarnLockVersion); + block.Title.Should().Be("block1"); + block.Children.Should().ContainSingle(); + block.Values["property"].Should().Be("value"); + block.Children.Single(x => x.Title == "block2").Values.Should().ContainKey("otherProperty"); + var value = block.Children.Single(x => x.Title == "block2").Values["otherProperty"]; + file.VersionHeader.Should().Be(yarnLockFileVersionString); + file.YarnLockVersion.Should().Be(YarnLockVersion.V2); } [TestMethod] @@ -237,12 +241,13 @@ public async Task BlockFileParserV2WithSingleBlock_ParsesWithQuotesAsync() var block = file.Single(); - Assert.AreEqual(block.Title, "block1"); - Assert.AreEqual(1, block.Children.Count); - Assert.AreEqual("value", block.Values["property"]); - Assert.AreEqual("otherValue", block.Children.Single(x => x.Title == "block2").Values["otherProperty"]); - Assert.AreEqual(yarnLockFileVersionString, file.VersionHeader); - Assert.AreEqual(YarnLockVersion.V2, file.YarnLockVersion); + block.Title.Should().Be("block1"); + block.Children.Should().ContainSingle(); + block.Values["property"].Should().Be("value"); + block.Children.Single(x => x.Title == "block2").Values.Should().ContainKey("otherProperty"); + var value = block.Children.Single(x => x.Title == "block2").Values["otherProperty"]; + file.VersionHeader.Should().Be(yarnLockFileVersionString); + file.YarnLockVersion.Should().Be(YarnLockVersion.V2); } [TestMethod] @@ -287,8 +292,8 @@ public async Task BlockFileParserV2WithMultipleBlocks_ParsesAsync() var file = await YarnBlockFile.CreateBlockFileAsync(stream); - Assert.AreEqual(3, file.Count()); - Assert.AreEqual(yarnLockFileVersionString, file.VersionHeader); - Assert.AreEqual(YarnLockVersion.V2, file.YarnLockVersion); + file.Should().HaveCount(3); + file.VersionHeader.Should().Be(yarnLockFileVersionString); + file.YarnLockVersion.Should().Be(YarnLockVersion.V2); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs index fd7f3c0f7..d45535042 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs @@ -55,8 +55,8 @@ public async Task WellFormedYarnLockV1WithZeroComponents_FindsNothingAsync() .WithFile("package.json", packageJson, new List { "package.json" }) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -70,8 +70,8 @@ public async Task WellFormedYarnLockV2WithZeroComponents_FindsNothingAsync() .WithFile("package.json", packageJson, new List { "package.json" }) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -99,8 +99,8 @@ public async Task MalformedYarnLockV1WithOneComponent_FindsNoComponentAsync() .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -126,8 +126,8 @@ public async Task MalformedYarnLockV2WithOneComponent_FindsNoComponentAsync() .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + componentRecorder.GetDetectedComponents().Count().Should().Be(0); } [TestMethod] @@ -150,12 +150,12 @@ public async Task WellFormedYarnLockV1WithOneComponent_FindsComponentAsync() .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); - Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); - Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); + detectedComponents.Should().ContainSingle(); + ((NpmComponent)detectedComponents.Single().Component).Name.Should().Be(componentA.Name); + ((NpmComponent)detectedComponents.Single().Component).Version.Should().Be(version0); componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, @@ -182,12 +182,12 @@ public async Task WellFormedYarnLockV2WithOneComponent_FindsComponentAsync() .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); - Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); - Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); + detectedComponents.Should().ContainSingle(); + ((NpmComponent)detectedComponents.Single().Component).Name.Should().Be(componentA.Name); + ((NpmComponent)detectedComponents.Single().Component).Version.Should().Be(version0); componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, @@ -228,12 +228,12 @@ public async Task WellFormedYarnLockV1WithWorkspace_FindsComponentAsync() .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); - Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); - Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); + detectedComponents.Should().ContainSingle(); + ((NpmComponent)detectedComponents.Single().Component).Name.Should().Be(componentA.Name); + ((NpmComponent)detectedComponents.Single().Component).Version.Should().Be(version0); componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, @@ -277,11 +277,11 @@ public async Task WellFormedYarnLockV1WithWorkspace_CheckFilePathsAsync() scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - detectedComponents.Should().HaveCount(1); + detectedComponents.Should().ContainSingle(); // checking if workspace's "package.json FilePath entry" is added or not. var detectedFilePaths = detectedComponents.First().FilePaths; - detectedFilePaths.Should().HaveCount(1); + detectedFilePaths.Should().ContainSingle(); var expectedWorkSpacePackageJsonPath = Path.Combine(Path.GetTempPath(), "workspace", "package.json"); detectedComponents.First().FilePaths.Contains(expectedWorkSpacePackageJsonPath).Should().Be(true); } @@ -320,12 +320,12 @@ public async Task WellFormedYarnLockV2WithWorkspace_FindsComponentAsync() .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); - Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); - Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); + detectedComponents.Should().ContainSingle(); + ((NpmComponent)detectedComponents.Single().Component).Name.Should().Be(componentA.Name); + ((NpmComponent)detectedComponents.Single().Component).Version.Should().Be(version0); componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, @@ -366,12 +366,12 @@ public async Task WellFormedYarnLockV1WithWorkspaceAltForm_FindsComponentAsync() .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); - Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); - Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); + detectedComponents.Should().ContainSingle(); + ((NpmComponent)detectedComponents.Single().Component).Name.Should().Be(componentA.Name); + ((NpmComponent)detectedComponents.Single().Component).Version.Should().Be(version0); componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, @@ -412,12 +412,12 @@ public async Task WellFormedYarnLockV2WithWorkspaceAltForm_FindsComponentAsync() .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); var detectedComponents = componentRecorder.GetDetectedComponents(); - Assert.AreEqual(1, detectedComponents.Count()); - Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); - Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); + detectedComponents.Should().ContainSingle(); + ((NpmComponent)detectedComponents.Single().Component).Name.Should().Be(componentA.Name); + ((NpmComponent)detectedComponents.Single().Component).Version.Should().Be(version0); componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, @@ -459,8 +459,8 @@ public async Task WellFormedYarnLockV1WithMoreThanOneComponent_FindsComponentsAs var component0 = detectedComponents.Select(x => x.Component).Cast().Single(x => x.Name == componentA.Name); var component1 = detectedComponents.Select(x => x.Component).Cast().Single(x => x.Name == componentB.Name); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(2, detectedComponents.Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + detectedComponents.Should().HaveCount(2); componentRecorder.AssertAllExplicitlyReferencedComponents( component0.Id, @@ -506,8 +506,8 @@ public async Task WellFormedYarnLockV2WithMoreThanOneComponent_FindsComponentsAs var component0 = detectedComponents.Select(x => x.Component).Cast().Single(x => x.Name == componentA.Name); var component1 = detectedComponents.Select(x => x.Component).Cast().Single(x => x.Name == componentB.Name); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(2, detectedComponents.Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + detectedComponents.Should().HaveCount(2); componentRecorder.AssertAllExplicitlyReferencedComponents( component0.Id, @@ -579,21 +579,21 @@ public async Task WellFormedYarnLockV1WithMultiRootedComponent_FindsAllRootsAsyn var componentA = detectedComponentes.Single(x => ((NpmComponent)x.Component).Name == componentNameA); var componentB = detectedComponentes.Single(x => ((NpmComponent)x.Component).Name == componentNameB); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(2, detectedComponentes.Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + detectedComponentes.Should().HaveCount(2); // Component A componentRecorder.AssertAllExplicitlyReferencedComponents( componentA.Component.Id, parentComponent => parentComponent.Id == componentA.Component.Id); - Assert.AreEqual(false, componentRecorder.GetEffectiveDevDependencyValue(componentA.Component.Id)); + componentRecorder.GetEffectiveDevDependencyValue(componentA.Component.Id).Should().Be(false); // Component B componentRecorder.AssertAllExplicitlyReferencedComponents( componentB.Component.Id, parentComponent1 => parentComponent1.Id == componentA.Component.Id, parentComponent2 => parentComponent2.Id == componentB.Component.Id); - Assert.AreEqual(false, componentRecorder.GetEffectiveDevDependencyValue(componentB.Component.Id)); + componentRecorder.GetEffectiveDevDependencyValue(componentB.Component.Id).Should().Be(false); } [TestMethod] @@ -655,21 +655,21 @@ public async Task WellFormedYarnLockV2WithMultiRootedComponent_FindsAllRootsAsyn var componentA = detectedComponentes.Single(x => ((NpmComponent)x.Component).Name == componentNameA); var componentB = detectedComponentes.Single(x => ((NpmComponent)x.Component).Name == componentNameB); - Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - Assert.AreEqual(2, detectedComponentes.Count()); + scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); + detectedComponentes.Should().HaveCount(2); // Component A componentRecorder.AssertAllExplicitlyReferencedComponents( componentA.Component.Id, parentComponent => parentComponent.Id == componentA.Component.Id); - Assert.AreEqual(false, componentRecorder.GetEffectiveDevDependencyValue(componentA.Component.Id)); + componentRecorder.GetEffectiveDevDependencyValue(componentA.Component.Id).Should().Be(false); // Component B componentRecorder.AssertAllExplicitlyReferencedComponents( componentB.Component.Id, parentComponent1 => parentComponent1.Id == componentA.Component.Id, parentComponent2 => parentComponent2.Id == componentB.Component.Id); - Assert.AreEqual(false, componentRecorder.GetEffectiveDevDependencyValue(componentB.Component.Id)); + componentRecorder.GetEffectiveDevDependencyValue(componentB.Component.Id).Should().Be(false); } [TestMethod] @@ -812,7 +812,7 @@ public async Task MalformedYarnLockV1_DuplicateAsync() var detectedComponents = componentRecorder.GetDetectedComponents(); - detectedComponents.Should().HaveCount(1); + detectedComponents.Should().ContainSingle(); var detectedComponent = detectedComponents.First(); } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs index e7ff7c6c7..0c76d03fb 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs @@ -3,6 +3,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System; using System.Collections.Generic; using System.Linq; +using FluentAssertions; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Detectors.Yarn; using Microsoft.ComponentDetection.Detectors.Yarn.Parsers; @@ -29,9 +30,9 @@ public void YarnLockParserWithNullBlockFile_Fails() { var parser = new YarnLockParser(this.loggerMock.Object); - void Action() => parser.Parse(this.recorderMock.Object, null, this.loggerMock.Object); + var action = () => parser.Parse(this.recorderMock.Object, null, this.loggerMock.Object); - Assert.ThrowsException(Action); + action.Should().ThrowExactly(); } [TestMethod] @@ -44,7 +45,7 @@ public void YarnLockParser_CanParseV1LockFiles() var blockFile = new Mock(); blockFile.Setup(x => x.YarnLockVersion).Returns(yarnLockFileVersion); - Assert.IsTrue(parser.CanParse(blockFile.Object.YarnLockVersion)); + parser.CanParse(blockFile.Object.YarnLockVersion).Should().BeTrue(); } [TestMethod] @@ -57,7 +58,7 @@ public void YarnLockParser_CanParseV2LockFiles() var blockFile = new Mock(); blockFile.Setup(x => x.YarnLockVersion).Returns(yarnLockFileVersion); - Assert.IsTrue(parser.CanParse(blockFile.Object.YarnLockVersion)); + parser.CanParse(blockFile.Object.YarnLockVersion).Should().BeTrue(); } [TestMethod] @@ -74,8 +75,8 @@ public void YarnLockParser_ParsesEmptyFile() var file = parser.Parse(this.recorderMock.Object, blockFile.Object, this.loggerMock.Object); - Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); - Assert.AreEqual(0, file.Entries.Count()); + file.LockVersion.Should().Be(YarnLockVersion.V1); + file.Entries.Should().BeEmpty(); } [TestMethod] @@ -104,8 +105,8 @@ public void YarnLockParser_ParsesBlocks() var file = parser.Parse(this.recorderMock.Object, blockFile.Object, this.loggerMock.Object); - Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); - Assert.AreEqual(3, file.Entries.Count()); + file.LockVersion.Should().Be(YarnLockVersion.V1); + file.Entries.Should().HaveCount(3); foreach (var entry in file.Entries) { @@ -140,11 +141,11 @@ public void YarnLockParser_ParsesNoVersionInTitleBlock() var file = parser.Parse(this.recorderMock.Object, blockFile.Object, this.loggerMock.Object); - Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); - Assert.AreEqual(2, file.Entries.Count()); + file.LockVersion.Should().Be(YarnLockVersion.V1); + file.Entries.Should().HaveCount(2); - Assert.IsNotNull(file.Entries.FirstOrDefault(x => x.LookupKey == "a@1.0.0")); - Assert.IsNotNull(file.Entries.FirstOrDefault(x => x.LookupKey == "b@2.4.6")); + file.Entries.FirstOrDefault(x => x.LookupKey == "a@1.0.0").Should().NotBeNull(); + file.Entries.FirstOrDefault(x => x.LookupKey == "b@2.4.6").Should().NotBeNull(); } private YarnBlock CreateDependencyBlock(IDictionary dependencies) @@ -185,15 +186,15 @@ private void AssertBlockMatchesEntry(YarnBlock block, YarnEntry entry) var componentName = block.Title.Split(',').Select(x => x.Trim()).First().Split('@')[0]; var blockVersions = block.Title.Split(',').Select(x => x.Trim()).Select(x => x.Split('@')[1]); - Assert.AreEqual(componentName, entry.Name); + entry.Name.Should().Be(componentName); foreach (var version in blockVersions) { - Assert.IsTrue(entry.Satisfied.Contains(YarnLockParser.NormalizeVersion(version))); + entry.Satisfied.Should().Contain(YarnLockParser.NormalizeVersion(version)); } - Assert.AreEqual(block.Values["version"], entry.Version); - Assert.AreEqual(block.Values["resolved"], entry.Resolved); + entry.Version.Should().Be(block.Values["version"]); + entry.Resolved.Should().Be(block.Values["resolved"]); var dependencies = block.Children.SingleOrDefault(x => x.Title == "dependencies"); @@ -201,7 +202,7 @@ private void AssertBlockMatchesEntry(YarnBlock block, YarnEntry entry) { foreach (var dependency in dependencies.Values) { - Assert.IsNotNull(entry.Dependencies.SingleOrDefault(x => x.Name == dependency.Key && x.Version == dependency.Value)); + entry.Dependencies.SingleOrDefault(x => x.Name == dependency.Key && x.Version == dependency.Value).Should().NotBeNull(); } } }