diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/CollectorNameValueConfigurationManagerTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/CollectorNameValueConfigurationManagerTests.cs index 4dcd550c11..3c63ef3158 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/CollectorNameValueConfigurationManagerTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/CollectorNameValueConfigurationManagerTests.cs @@ -41,13 +41,13 @@ public void ConstructorShouldNotInitializeNameValuePairIfEmptyXmlElementIsPassed } var configManager = new CollectorNameValueConfigurationManager(xmlDocument.DocumentElement); - Assert.AreEqual(0, configManager.NameValuePairs.Count); + Assert.IsEmpty(configManager.NameValuePairs); } [TestMethod] public void ConstructorShouldNotInitializeNameValuePairNullIsPassed() { var configManager = new CollectorNameValueConfigurationManager(null); - Assert.AreEqual(0, configManager.NameValuePairs.Count); + Assert.IsEmpty(configManager.NameValuePairs); } } diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogContainerTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogContainerTests.cs index 72727cbb4a..0e77ce605a 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogContainerTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogContainerTests.cs @@ -60,7 +60,7 @@ public void OnEventLogEntryWrittenShouldAddLogs() _eventLogContainer.OnEventLogEntryWritten(_eventLog, _entryWrittenEventArgs); var newCount = _eventLogContainer.EventLogEntries.Count; - Assert.IsTrue(newCount > 0); + Assert.IsGreaterThan(0, newCount); } [TestMethod] diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs index d977b765b1..fda7431395 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs @@ -220,21 +220,21 @@ public void InitializeShouldSubscribeToDataCollectionEvents() public void TestSessionStartEventShouldCreateEventLogContainer() { var eventLogDataCollector = new EventLogDataCollector(); - Assert.AreEqual(0, eventLogDataCollector.ContextMap.Count); + Assert.IsEmpty(eventLogDataCollector.ContextMap); eventLogDataCollector.Initialize(null, _mockDataCollectionEvents.Object, _mockDataCollectionSink, _mockDataCollectionLogger.Object, _dataCollectionEnvironmentContext); _mockDataCollectionEvents.Raise(x => x.SessionStart += null, new SessionStartEventArgs()); - Assert.AreEqual(1, eventLogDataCollector.ContextMap.Count); + Assert.HasCount(1, eventLogDataCollector.ContextMap); } [TestMethod] public void TestCaseStartEventShouldCreateEventLogContainer() { var eventLogDataCollector = new EventLogDataCollector(); - Assert.AreEqual(0, eventLogDataCollector.ContextMap.Count); + Assert.IsEmpty(eventLogDataCollector.ContextMap); eventLogDataCollector.Initialize(null, _mockDataCollectionEvents.Object, _mockDataCollectionSink, _mockDataCollectionLogger.Object, _dataCollectionEnvironmentContext); _mockDataCollectionEvents.Raise(x => x.TestCaseStart += null, new TestCaseStartEventArgs(new DataCollectionContext(new SessionId(Guid.NewGuid()), new TestExecId(Guid.NewGuid())), new TestCase())); - Assert.AreEqual(1, eventLogDataCollector.ContextMap.Count); + Assert.HasCount(1, eventLogDataCollector.ContextMap); } [TestMethod] diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogSessionContextTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogSessionContextTests.cs index cb5e7dd4dd..82d693be93 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogSessionContextTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogSessionContextTests.cs @@ -29,7 +29,7 @@ public EventLogSessionContextTests() public void CreateEventLogContainerStartIndexMapShouldCreateStartIndexMap() { _eventLogSessionContext = new EventLogSessionContext(_eventLogContainersMap); - Assert.IsTrue(_eventLogSessionContext.EventLogContainerStartIndexMap["LogName"] == 2); + Assert.AreEqual(2, _eventLogSessionContext.EventLogContainerStartIndexMap["LogName"]); } [TestMethod] @@ -37,7 +37,7 @@ public void CreateEventLogContainerEndIndexMapShouldCreateEndIndexMap() { _eventLogSessionContext = new EventLogSessionContext(_eventLogContainersMap); _eventLogSessionContext.CreateEventLogContainerEndIndexMap(); - Assert.IsTrue(_eventLogSessionContext.EventLogContainerEndIndexMap["LogName"] == 1); + Assert.AreEqual(1, _eventLogSessionContext.EventLogContainerEndIndexMap["LogName"]); } [TestMethod] @@ -47,8 +47,8 @@ public void CreateEventLogContainerShouldNotAddIndexEntriesIfEventLogContainerMa _eventLogSessionContext.CreateEventLogContainerStartIndexMap(); _eventLogSessionContext.CreateEventLogContainerEndIndexMap(); - Assert.IsTrue(_eventLogSessionContext.EventLogContainerStartIndexMap.Count == 0); - Assert.IsTrue(_eventLogSessionContext.EventLogContainerEndIndexMap.Count == 0); + Assert.IsEmpty(_eventLogSessionContext.EventLogContainerStartIndexMap); + Assert.IsEmpty(_eventLogSessionContext.EventLogContainerEndIndexMap); } [TestMethod] @@ -62,8 +62,8 @@ public void CreateEventLogContainerShouldCreateNegativeEndIndexIfLogEntriesAreEm _eventLogSessionContext.CreateEventLogContainerStartIndexMap(); _eventLogSessionContext.CreateEventLogContainerEndIndexMap(); - Assert.IsTrue(_eventLogSessionContext.EventLogContainerStartIndexMap["DummyEventLog"] == 0); - Assert.IsTrue(_eventLogSessionContext.EventLogContainerEndIndexMap["DummyEventLog"] == -1); + Assert.AreEqual(0, _eventLogSessionContext.EventLogContainerStartIndexMap["DummyEventLog"]); + Assert.AreEqual(-1, _eventLogSessionContext.EventLogContainerEndIndexMap["DummyEventLog"]); } } diff --git a/test/Directory.Build.props b/test/Directory.Build.props index b93c6783d2..f98e859cc3 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -3,13 +3,18 @@ true + + $(NoWarn);MSTEST0001 true true + Recommended diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs index e551f33c05..40c56b9dce 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs @@ -98,7 +98,7 @@ public void BlameDataCollectorShouldNotOutputDumpFileWhenNoCrashOccurs(RunnerInf InvokeVsTest(arguments, env); - Assert.IsFalse(StdOut.Contains(".dmp"), "it should not collect a dump, because nothing crashed"); + Assert.DoesNotContain(".dmp", StdOut, "it should not collect a dump, because nothing crashed"); } [TestMethod] @@ -122,7 +122,7 @@ public void BlameDataCollectorShouldOutputDumpFileWhenNoCrashOccursButCollectAlw InvokeVsTest(arguments, env); - StringAssert.Matches(StdOut, new Regex("\\.dmp"), "it should collect dump, even if nothing crashed"); + Assert.MatchesRegex(new Regex("\\.dmp"), StdOut, "it should collect dump, even if nothing crashed"); } [TestMethod] @@ -260,7 +260,7 @@ public void BlameDataCollectorAeDebuggerShouldCollectDump(RunnerInfo runnerInfo) out string standardTestOutput, out string standardErrorTestOutput, out int _); - Assert.IsTrue(standardErrorTestOutput.Trim().Length == 0); + Assert.AreEqual(0, standardErrorTestOutput.Trim().Length); // Run test under postmortem monitoring var assemblyPaths = GetAssetFullPath("BlameUnitTestProject.dll"); @@ -274,12 +274,12 @@ public void BlameDataCollectorAeDebuggerShouldCollectDump(RunnerInfo runnerInfo) out standardTestOutput, out standardErrorTestOutput, out int _); - Assert.IsTrue(standardErrorTestOutput.Trim().Length == 0); + Assert.AreEqual(0, standardErrorTestOutput.Trim().Length); // We cannot be precise here procdump is at machine level so we can have more than one dump and not only the one for our test // We look for "at least" one dump file, is the best we can do without locking all tests. - Assert.IsTrue(Directory.GetFiles(TempDirectory.Path, "*.dmp", SearchOption.AllDirectories) - .Where(x => Path.GetFileNameWithoutExtension(x).StartsWith("testhost")).Count() > 0); + Assert.IsNotEmpty(Directory.GetFiles(TempDirectory.Path, "*.dmp", SearchOption.AllDirectories) + .Where(x => Path.GetFileNameWithoutExtension(x).StartsWith("testhost"))); } private static bool IsAdministrator() diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Build.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Build.cs index 6665e1cdbc..fcb06b3119 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Build.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Build.cs @@ -7,7 +7,7 @@ namespace Microsoft.TestPlatform.Acceptance.IntegrationTests; [TestClass] -public class Build : IntegrationTestBase +public static class Build { [AssemblyInitialize] public static void AssemblyInitialize(TestContext testContext) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/CodeCoverageTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/CodeCoverageTests.cs index 9bad647034..e996c95a06 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/CodeCoverageTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/CodeCoverageTests.cs @@ -310,7 +310,7 @@ private static void AssertSkippedMethod(CoverageReport coverageReport) Assert.IsNotNull(module); var coverage = double.Parse(module.BlockCoverage, CultureInfo.InvariantCulture); - Assert.IsTrue(coverage > ExpectedMinimalModuleCoverage); + Assert.IsGreaterThan(ExpectedMinimalModuleCoverage, coverage); var testSignFunction = module.SkippedFunctions.FirstOrDefault(f => f.Name.Equals("TestSign()")); Assert.IsNotNull(testSignFunction); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs index 2ff6512274..d355b8f63b 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs @@ -140,7 +140,7 @@ public void DataCollectorAttachmentProcessor(RunnerInfo runnerInfo) while (!streamReader.EndOfStream) { string? line = streamReader.ReadLine(); - Assert.IsTrue(line!.StartsWith("SessionEnded_Handler_")); + Assert.StartsWith("SessionEnded_Handler_", line!); fileContent.Add(line); } } @@ -152,8 +152,8 @@ public void DataCollectorAttachmentProcessor(RunnerInfo runnerInfo) foreach (var dataCollectorLogFile in dataCollectorsLogs) { string dataCollectorLog = File.ReadAllText(dataCollectorLogFile); - Assert.IsTrue(dataCollectorLog.Contains("MetadataReaderExtensionsHelper: Valid extension found: extension type 'DataCollector' identifier 'my://sample/datacollector' implementation 'AttachmentProcessorDataCollector.SampleDataCollectorV1' version '1'")); - Assert.IsTrue(dataCollectorLog.Contains("MetadataReaderExtensionsHelper: Valid extension found: extension type 'DataCollector' identifier 'my://sample/datacollector' implementation 'AttachmentProcessorDataCollector.SampleDataCollectorV2' version '2'")); + Assert.Contains("MetadataReaderExtensionsHelper: Valid extension found: extension type 'DataCollector' identifier 'my://sample/datacollector' implementation 'AttachmentProcessorDataCollector.SampleDataCollectorV1' version '1'", dataCollectorLog); + Assert.Contains("MetadataReaderExtensionsHelper: Valid extension found: extension type 'DataCollector' identifier 'my://sample/datacollector' implementation 'AttachmentProcessorDataCollector.SampleDataCollectorV2' version '2'", dataCollectorLog); Assert.IsTrue(Regex.IsMatch(dataCollectorLog, @"GetTestExtensionFromType: Discovered multiple test extensions with identifier data 'my://sample/datacollector' and type 'AttachmentProcessorDataCollector\.SampleDataCollectorV1, AttachmentProcessorDataCollector, Version=.*, Culture=neutral, PublicKeyToken=null' inside file '.*AttachmentProcessorDataCollector\.dll'; keeping the first one 'AttachmentProcessorDataCollector\.SampleDataCollectorV2, AttachmentProcessorDataCollector, Version=.*, Culture=neutral, PublicKeyToken=null'\.")); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs index 0c72b79fa5..91d5102608 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs @@ -52,11 +52,11 @@ public void Create_ShouldReturnListOfAttachmentProcessors() var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); // assert - Assert.AreEqual(3, dataCollectorAttachmentsProcessors.Length); + Assert.HasCount(3, dataCollectorAttachmentsProcessors); - Assert.AreEqual(1, dataCollectorAttachmentsProcessors.Count(x => x.FriendlyName == "Sample")); - Assert.AreEqual(1, dataCollectorAttachmentsProcessors.Count(x => x.FriendlyName == "SampleData3")); - Assert.AreEqual(1, dataCollectorAttachmentsProcessors.Count(x => x.FriendlyName == "Code Coverage")); + Assert.ContainsSingle(dataCollectorAttachmentsProcessors.Where(x => x.FriendlyName == "Sample")); + Assert.ContainsSingle(dataCollectorAttachmentsProcessors.Where(x => x.FriendlyName == "SampleData3")); + Assert.ContainsSingle(dataCollectorAttachmentsProcessors.Where(x => x.FriendlyName == "Code Coverage")); Assert.AreEqual(typeof(DataCollectorAttachmentProcessor).AssemblyQualifiedName, dataCollectorAttachmentsProcessors[0].DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName); Assert.AreEqual(typeof(DataCollectorAttachmentProcessor2).AssemblyQualifiedName, dataCollectorAttachmentsProcessors[1].DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName); @@ -72,7 +72,7 @@ public void Create_EmptyOrNullInvokedDataCollector_ShouldReturnCodeCoverageDataA var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(empty ? [] : null, null); //assert - Assert.AreEqual(1, dataCollectorAttachmentsProcessors.Length); + Assert.ContainsSingle(dataCollectorAttachmentsProcessors); Assert.AreEqual(typeof(CodeCoverageDataAttachmentsHandler).AssemblyQualifiedName, dataCollectorAttachmentsProcessors[0].DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName); } @@ -91,7 +91,7 @@ public void Create_ShouldNotFailIfWrongDataCollectorAttachmentProcessor() var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); // assert - Assert.AreEqual(1, dataCollectorAttachmentsProcessors.Length); + Assert.ContainsSingle(dataCollectorAttachmentsProcessors); Assert.AreEqual(typeof(CodeCoverageDataAttachmentsHandler).AssemblyQualifiedName, dataCollectorAttachmentsProcessors[0].DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName); } @@ -108,7 +108,7 @@ public void Create_ShouldAddTwoTimeCodeCoverageDataAttachmentsHandler() var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); // assert - Assert.AreEqual(2, dataCollectorAttachmentsProcessors.Length); + Assert.HasCount(2, dataCollectorAttachmentsProcessors); Assert.AreEqual(typeof(DataCollectorAttachmentProcessor).AssemblyQualifiedName, dataCollectorAttachmentsProcessors[0].DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName); Assert.AreEqual(typeof(CodeCoverageDataAttachmentsHandler).AssemblyQualifiedName, dataCollectorAttachmentsProcessors[1].DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName); } @@ -141,7 +141,7 @@ public void Create_ShouldLoadOrderingByFilePath() var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); // assert - Assert.AreEqual(2, dataCollectorAttachmentsProcessors.Length); + Assert.HasCount(2, dataCollectorAttachmentsProcessors); Assert.IsTrue(Regex.IsMatch(dataCollectorAttachmentsProcessors[0].DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName!, @"AttachmentProcessorDataCollector\.SampleDataCollectorAttachmentProcessor, AttachmentProcessorDataCollector, Version=.*, Culture=neutral, PublicKeyToken=null")); Assert.AreEqual(Path.Combine(version2, Path.GetFileName(dataCollectorFilePath)), dataCollectorAttachmentsProcessors[0].DataCollectorAttachmentProcessorInstance.GetType().Assembly.Location); Assert.AreEqual(typeof(CodeCoverageDataAttachmentsHandler).AssemblyQualifiedName, dataCollectorAttachmentsProcessors[1].DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorTests.Coverlet.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorTests.Coverlet.cs index 9931acf617..bef9bd5c77 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorTests.Coverlet.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorTests.Coverlet.cs @@ -41,15 +41,15 @@ public void RunCoverletCoverage() // This assert check that we're sure that we've updated collector setting code base with full path, // otherwise without "custom coverlet code" inside ProxyExecutionManager coverlet dll won't be resolved inside testhost. var log = Directory.GetFiles(logPathDirectory, $"coverletcoverage.{logId}.log").Single(); - Assert.IsTrue(File.ReadAllText(log).Contains("CoverletDataCollector in-process codeBase path")); + Assert.Contains("CoverletDataCollector in-process codeBase path", File.ReadAllText(log)); // Verify out-of-proc coverlet collector load var dataCollectorLog = Directory.GetFiles(logPathDirectory, $"coverletcoverage.{logId}.datacollector*log").Single(); - Assert.IsTrue(File.ReadAllText(dataCollectorLog).Contains("[coverlet]Initializing CoverletCoverageDataCollector")); + Assert.Contains("[coverlet]Initializing CoverletCoverageDataCollector", File.ReadAllText(dataCollectorLog)); // Verify in-proc coverlet collector load var hostLog = Directory.GetFiles(logPathDirectory, $"coverletcoverage.{logId}.host*log").Single(); - Assert.IsTrue(File.ReadAllText(hostLog).Contains("[coverlet]Initialize CoverletInProcDataCollector")); + Assert.Contains("[coverlet]Initialize CoverletInProcDataCollector", File.ReadAllText(hostLog)); // Verify default coverage file is generated StdOutputContains("coverage.cobertura.xml"); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DebugAssertTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DebugAssertTests.cs index abff214c4a..d6578bb9d8 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DebugAssertTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DebugAssertTests.cs @@ -25,6 +25,6 @@ public void RunningTestWithAFailingDebugAssertDoesNotCrashTheHostingProcess(Runn // this will have failed tests when our trace listener works and crash the testhost process when it does not // because crashing processes is what a failed TPDebug.Assert does by default, unless you have a debugger attached ValidateSummaryStatus(passed: 4, failed: 4, 0); - StringAssert.Contains(StdOut, "threw exception: Microsoft.VisualStudio.TestPlatform.TestHost.DebugAssertException:"); + Assert.Contains("threw exception: Microsoft.VisualStudio.TestPlatform.TestHost.DebugAssertException:", StdOut); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs index fc536f97b4..3680b3c9bc 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs @@ -87,8 +87,8 @@ public void DiscoverTestsShouldShowProperWarningIfNoTestsOnTestCaseFilter(Runner arguments = string.Concat(arguments, " /logger:\"console;prefix=true\""); InvokeVsTest(arguments); - StringAssert.Contains(StdOut, "Warning: No test matches the given testcase filter `NonExistTestCaseName` in"); - StringAssert.Contains(StdOut, "SimpleTestProject2.dll"); + Assert.Contains("Warning: No test matches the given testcase filter `NonExistTestCaseName` in", StdOut); + Assert.Contains("SimpleTestProject2.dll", StdOut); ExitCodeEquals(0); } @@ -136,7 +136,7 @@ public void DiscoverTestsShouldSucceedWhenAtLeastOneDllFindsRuntimeProvider(Runn arguments = string.Concat(arguments, " /logger:\"console;prefix=true\""); InvokeVsTest(arguments); - StringAssert.Contains(StdOut, $"Skipping source: {nonTestDll} (.NETStandard,Version=v2.0,"); + Assert.Contains($"Skipping source: {nonTestDll} (.NETStandard,Version=v2.0,", StdOut); ExitCodeEquals(0); } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DotnetArchitectureSwitchTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DotnetArchitectureSwitchTests.cs index b0d18da897..c0504923c6 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DotnetArchitectureSwitchTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DotnetArchitectureSwitchTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if !NETFRAMEWORK @@ -40,13 +40,9 @@ public static void ClassCleanup() } [TestMethod] + [OSCondition(OperatingSystems.Windows | OperatingSystems.OSX)] public void GlobalInstallation() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return; - } - var projectName = "ArchitectureSwitch.csproj"; var projectPath = GetProjectFullPath(projectName); var projectDirectory = Path.GetDirectoryName(projectPath); @@ -60,14 +56,14 @@ public void GlobalInstallation() ExecuteApplication(GetDefaultDotnetMuxerLocation, $"test {projectPath} --framework net8.0", out string stdOut, out _, out _, env, projectDirectory); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - Assert.IsTrue(stdOut.Contains("Runtime location: /usr/local/share/dotnet/shared/Microsoft.NETCore.App")); + Assert.Contains("Runtime location: /usr/local/share/dotnet/shared/Microsoft.NETCore.App", stdOut); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - Assert.IsTrue(stdOut.Contains($@"Runtime location: {Environment.ExpandEnvironmentVariables("%ProgramFiles%")}\dotnet\shared\Microsoft.NETCore.App")); + Assert.Contains($@"Runtime location: {Environment.ExpandEnvironmentVariables("%ProgramFiles%")}\dotnet\shared\Microsoft.NETCore.App", stdOut); } - Assert.IsTrue(stdOut.Contains("OSArchitecture: ARM64")); - Assert.IsTrue(stdOut.Contains("ProcessArchitecture: ARM64")); + Assert.Contains("OSArchitecture: ARM64", stdOut); + Assert.Contains("ProcessArchitecture: ARM64", stdOut); // Verify switch using csproj @@ -83,27 +79,23 @@ static void AssertSwitch(string output) { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - Assert.IsTrue(output.Contains("Runtime location: /usr/local/share/dotnet/x64/shared/Microsoft.NETCore.App")); + Assert.Contains("Runtime location: /usr/local/share/dotnet/x64/shared/Microsoft.NETCore.App", output); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - Assert.IsTrue(output.Contains($@"Runtime location: {Environment.ExpandEnvironmentVariables("%ProgramFiles%")}\dotnet\x64\shared\Microsoft.NETCore.App")); + Assert.Contains($@"Runtime location: {Environment.ExpandEnvironmentVariables("%ProgramFiles%")}\dotnet\x64\shared\Microsoft.NETCore.App", output); } - Assert.IsTrue(output.Contains("OSArchitecture: X64")); - Assert.IsTrue(output.Contains("ProcessArchitecture: X64")); + Assert.Contains("OSArchitecture: X64", output); + Assert.Contains("ProcessArchitecture: X64", output); } } [TestMethod] [DataRow(true, false)] [DataRow(false, true)] + [OSCondition(OperatingSystems.Windows | OperatingSystems.OSX)] public void DOTNET_ROOTS_EnvironmentVariables(bool dotnetRoot, bool dotnetRootX64) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return; - } - var env = new Dictionary { ["DOTNET_ROOT"] = null @@ -117,14 +109,14 @@ public void DOTNET_ROOTS_EnvironmentVariables(bool dotnetRoot, bool dotnetRootX6 ExecuteApplication(GetDefaultDotnetMuxerLocation, $"test {projectPath} --framework net8.0", out string stdOut, out _, out _, env, projectDirectory); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - Assert.IsTrue(stdOut.Contains("Runtime location: /usr/local/share/dotnet/shared/Microsoft.NETCore.App"), "Unexpected runtime location"); + Assert.Contains("Runtime location: /usr/local/share/dotnet/shared/Microsoft.NETCore.App", stdOut, "Unexpected runtime location"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - Assert.IsTrue(stdOut.Contains($@"Runtime location: {Environment.ExpandEnvironmentVariables("%ProgramFiles%")}\dotnet\shared\Microsoft.NETCore.App")); + Assert.Contains($@"Runtime location: {Environment.ExpandEnvironmentVariables("%ProgramFiles%")}\dotnet\shared\Microsoft.NETCore.App", stdOut); } - Assert.IsTrue(stdOut.Contains("OSArchitecture: ARM64"), "Unexpected OSArchitecture"); - Assert.IsTrue(stdOut.Contains("ProcessArchitecture: ARM64"), "Unexpected ProcessArchitecture"); + Assert.Contains("OSArchitecture: ARM64", stdOut, "Unexpected OSArchitecture"); + Assert.Contains("ProcessArchitecture: ARM64", stdOut, "Unexpected ProcessArchitecture"); env.Clear(); env["DOTNET_ROOT"] = null; @@ -150,21 +142,17 @@ public void DOTNET_ROOTS_EnvironmentVariables(bool dotnetRoot, bool dotnetRootX6 void AssertSwitch(string output) { Assert.IsTrue(Regex.IsMatch(output.Replace(@"\", "/"), $"Runtime location: .*{s_privateX64Installation.Replace(@"\", "/")}.*shared.*Microsoft.NETCore.App"), "Unexpected runtime location"); - Assert.IsTrue(output.Contains("OSArchitecture: X64"), "Unexpected OSArchitecture"); - Assert.IsTrue(output.Contains("ProcessArchitecture: X64"), "Unexpected ProcessArchitecture"); + Assert.Contains("OSArchitecture: X64", output, "Unexpected OSArchitecture"); + Assert.Contains("ProcessArchitecture: X64", output, "Unexpected ProcessArchitecture"); Assert.IsTrue(!dotnetRoot || output.Contains($"DOTNET_ROOT: {s_privateX64Installation}"), "Unexpected DOTNET_ROOT var"); Assert.IsTrue(!dotnetRootX64 || output.Contains($"DOTNET_ROOT_X64: {s_privateX64Installation}"), "Unexpected DOTNET_ROOT_X64 var"); } } [TestMethod] + [OSCondition(OperatingSystems.Windows | OperatingSystems.OSX)] public void PrivateX64BuildToGlobalArmInstallation() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return; - } - var env = new Dictionary { ["DOTNET_ROOT"] = null @@ -178,8 +166,8 @@ public void PrivateX64BuildToGlobalArmInstallation() // Verify native architecture ExecuteApplication(privateInstallationMuxer, $"test {projectPath} --framework net8.0", out string stdOut, out _, out _, env, projectDirectory); Assert.IsTrue(Regex.IsMatch(stdOut.Replace(@"\", "/"), $"Runtime location: .*{s_privateX64Installation.Replace(@"\", "/")}.*shared.*Microsoft.NETCore.App"), "Unexpected runtime location"); - Assert.IsTrue(stdOut.Contains("OSArchitecture: X64"), "Unexpected OSArchitecture"); - Assert.IsTrue(stdOut.Contains("ProcessArchitecture: X64"), "Unexpected ProcessArchitecture"); + Assert.Contains("OSArchitecture: X64", stdOut, "Unexpected OSArchitecture"); + Assert.Contains("ProcessArchitecture: X64", stdOut, "Unexpected ProcessArchitecture"); // Verify switch using csproj ExecuteApplication($"{s_privateX64Installation}/{GetMuxerName}", $"test {projectPath} --framework net8.0 --arch arm64", out stdOut, out _, out _, env, projectDirectory); @@ -193,21 +181,17 @@ public void PrivateX64BuildToGlobalArmInstallation() static void AssertSwitch(string output) { Assert.IsTrue(Regex.IsMatch(output.Replace(@"\", "/"), $"Runtime location: .*{GetDefaultLocation.Replace(@"\", "/")}.*shared.*Microsoft.NETCore.App"), "Unexpected runtime location"); - Assert.IsTrue(output.Contains("OSArchitecture: ARM64"), "Unexpected OSArchitecture"); - Assert.IsTrue(output.Contains("ProcessArchitecture: ARM64"), "Unexpected ProcessArchitecture"); + Assert.Contains("OSArchitecture: ARM64", output, "Unexpected OSArchitecture"); + Assert.Contains("ProcessArchitecture: ARM64", output, "Unexpected ProcessArchitecture"); } } [TestMethod] [DataRow(true, false)] [DataRow(false, true)] + [OSCondition(OperatingSystems.Windows | OperatingSystems.OSX)] public void PrivateX64BuildToDOTNET_ROOTS_EnvironmentVariables(bool dotnetRoot, bool dotnetRootArm64) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return; - } - var env = new Dictionary { ["DOTNET_ROOT"] = null @@ -221,8 +205,8 @@ public void PrivateX64BuildToDOTNET_ROOTS_EnvironmentVariables(bool dotnetRoot, // Verify native architecture ExecuteApplication(privateInstallationMuxer, $"test {projectPath} --framework net8.0", out string stdOut, out _, out _, env, projectDirectory); Assert.IsTrue(Regex.IsMatch(stdOut.Replace(@"\", "/"), $"Runtime location: .*{s_privateX64Installation.Replace(@"\", "/")}.*shared.*Microsoft.NETCore.App"), "Unexpected runtime location"); - Assert.IsTrue(stdOut.Contains("OSArchitecture: X64"), "Unexpected OSArchitecture"); - Assert.IsTrue(stdOut.Contains("ProcessArchitecture: X64"), "Unexpected ProcessArchitecture"); + Assert.Contains("OSArchitecture: X64", stdOut, "Unexpected OSArchitecture"); + Assert.Contains("ProcessArchitecture: X64", stdOut, "Unexpected ProcessArchitecture"); env.Clear(); env["DOTNET_ROOT"] = null; @@ -248,21 +232,17 @@ public void PrivateX64BuildToDOTNET_ROOTS_EnvironmentVariables(bool dotnetRoot, void AssertSwitch(string output) { Assert.IsTrue(Regex.IsMatch(output.Replace(@"\", "/"), $"Runtime location: .*{GetDefaultLocation.Replace(@"\", "/")}.*shared.*Microsoft.NETCore.App"), "Unexpected runtime location"); - Assert.IsTrue(output.Contains("OSArchitecture: ARM64"), "Unexpected OSArchitecture"); - Assert.IsTrue(output.Contains("ProcessArchitecture: ARM64"), "Unexpected ProcessArchitecture"); + Assert.Contains("OSArchitecture: ARM64", output, "Unexpected OSArchitecture"); + Assert.Contains("ProcessArchitecture: ARM64", output, "Unexpected ProcessArchitecture"); Assert.IsTrue(!dotnetRoot || output.Contains($"DOTNET_ROOT: {GetDefaultLocation}"), "Unexpected DOTNET_ROOT var"); Assert.IsTrue(!dotnetRootArm64 || output.Contains($"DOTNET_ROOT_ARM64: {GetDefaultLocation}"), "Unexpected DOTNET_ROOT_ARM64 var"); } } [TestMethod] + [OSCondition(OperatingSystems.Windows | OperatingSystems.OSX)] public void SilentlyForceX64() { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return; - } - var projectName = "ArchitectureSwitch.csproj"; var projectPath = GetProjectFullPath(projectName); var projectDirectory = Path.GetDirectoryName(projectPath); @@ -274,14 +254,14 @@ public void SilentlyForceX64() ExecuteApplication(GetDefaultDotnetMuxerLocation, $"test {projectPath} --framework {GetFrameworkVersionToForceToX64}", out string stdOut, out _, out _, env, projectDirectory); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - Assert.IsTrue(stdOut.Contains("Runtime location: /usr/local/share/dotnet/x64/shared/Microsoft.NETCore.App")); + Assert.Contains("Runtime location: /usr/local/share/dotnet/x64/shared/Microsoft.NETCore.App", stdOut); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - Assert.IsTrue(stdOut.Contains($@"Runtime location: {Environment.ExpandEnvironmentVariables("%ProgramFiles%")}\dotnet\x64\shared\Microsoft.NETCore.App")); + Assert.Contains($@"Runtime location: {Environment.ExpandEnvironmentVariables("%ProgramFiles%")}\dotnet\x64\shared\Microsoft.NETCore.App", stdOut); } - Assert.IsTrue(stdOut.Contains("OSArchitecture: X64")); - Assert.IsTrue(stdOut.Contains("ProcessArchitecture: X64")); + Assert.Contains("OSArchitecture: X64", stdOut); + Assert.Contains("ProcessArchitecture: X64", stdOut); } private static string GetMuxerName => RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "dotnet" : "dotnet.exe"; diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs index abadb1e3e5..4eeb03dcfb 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs @@ -92,7 +92,7 @@ private void VaildateDataCollectorOutput(TempDirectory tempDirectory) .Select(d => d.FullName) .ToList(); - Assert.AreEqual(4, resultFiles.Count); + Assert.HasCount(4, resultFiles); StdOutputContains("Event Log.xml"); var fileContent1 = File.ReadAllText(resultFiles[0]); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/ExecutionTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/ExecutionTests.cs index 37521595e2..f19d76ad79 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/ExecutionTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/ExecutionTests.cs @@ -391,7 +391,7 @@ public void ExecuteTestsShouldSucceedWhenAtLeastOneDllFindsRuntimeProvider(Runne arguments = string.Concat(arguments, " /logger:\"console;prefix=true\""); InvokeVsTest(arguments); - StringAssert.Contains(StdOut, $"Skipping source: {nonTestDll} (.NETStandard,Version=v2.0,"); + Assert.Contains($"Skipping source: {nonTestDll} (.NETStandard,Version=v2.0,", StdOut); ExitCodeEquals(1); } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs index 4bf30e4da6..6ff4e474ca 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs @@ -122,7 +122,7 @@ public void TrxLoggerWithLogFilePrefixShouldGenerateMultipleTrx(RunnerInfo runne InvokeVsTest(arguments); var trxFilePaths = Directory.EnumerateFiles(TempDirectory.Path, trxFileNamePattern + "_net*.trx"); - Assert.IsTrue(trxFilePaths.Count() > 1); + Assert.IsGreaterThan(1, trxFilePaths.Count()); } [TestMethod] @@ -194,7 +194,7 @@ public void TrxLoggerResultSummaryOutcomeValueShouldNotChangeIfNoTestsExecutedAn private static void AssertExpectedHtml(XmlElement root) { XmlNodeList elementList = root.GetElementsByTagName("details"); - Assert.AreEqual(2, elementList.Count); + Assert.HasCount(2, elementList); foreach (XmlElement element in elementList) { @@ -236,7 +236,7 @@ private static void IsFileAndContentEqual(string filePath) string[] divs = ["Total tests", "Passed", "Failed", "Skipped", "Run duration", "Pass percentage", "PassingTest"]; foreach (string str in divs) { - StringAssert.Contains(filePathContent, str); + Assert.Contains(str, filePathContent); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/ManagedNameTests/SpecialNameTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/ManagedNameTests/SpecialNameTests.cs index 28a2de5f37..007d4fd4e3 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/ManagedNameTests/SpecialNameTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/ManagedNameTests/SpecialNameTests.cs @@ -46,7 +46,7 @@ public void VerifyThatInvalidIdentifierNamesAreParsed() var methodInfo = ManagedNameHelper.GetMethod(assembly, typeName, methodName); ManagedNameHelper.GetManagedName(methodInfo, out var typeName2, out var methodName2); - Assert.IsTrue(method == methodInfo); + Assert.AreEqual(method, methodInfo); Assert.AreEqual(typeName, typeName2, $"Type parse roundtrip test failed: {method} ({typeName} != {typeName2})"); Assert.AreEqual(methodName, methodName2, $"Method parse roundtrip test failed: {method} ({methodName} != {methodName2})"); } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/PostProcessingTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/PostProcessingTests.cs index 964ddb1b0c..6dbc197592 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/PostProcessingTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/PostProcessingTests.cs @@ -72,7 +72,7 @@ public void DotnetSDKSimulation_PostProcessing() while (!streamReader.EndOfStream) { string line = streamReader.ReadLine(); - Assert.IsTrue(line.StartsWith("SessionEnded_Handler_")); + Assert.StartsWith("SessionEnded_Handler_", line); fileContent.Add(line); } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/VideoRecorderTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/VideoRecorderTests.cs index 0c12398d07..9f259f39d9 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/VideoRecorderTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/VideoRecorderTests.cs @@ -27,7 +27,7 @@ public void VideoRecorderDataCollectorShouldRecordVideoWithRunSettings(RunnerInf // Verify video attachments were created var resultFiles = Directory.GetFiles(TempDirectory.Path, "*.wmv", SearchOption.AllDirectories); - Assert.IsTrue(resultFiles.Length > 0, + Assert.IsNotEmpty(resultFiles, $"Expected video attachments (.wmv) in results directory '{TempDirectory.Path}', but found none. " + $"All files: [{string.Join(", ", Directory.GetFiles(TempDirectory.Path, "*", SearchOption.AllDirectories).Select(Path.GetFileName))}]"); } diff --git a/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs b/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs index a8ed80b8f1..d16be041df 100644 --- a/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs +++ b/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs @@ -36,9 +36,9 @@ public void CreateArgumentShouldAddOneEntryForCLIRunSettings() var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, " -- "); - StringAssert.Contains(commandline, $"\"{arg1}\""); - StringAssert.Contains(commandline, $"{arg2}"); + Assert.Contains(" -- ", commandline); + Assert.Contains($"\"{arg1}\"", commandline); + Assert.Contains($"{arg2}", commandline); } [TestMethod] @@ -58,9 +58,9 @@ public void CreateArgumentShouldAddCLIRunSettingsArgAtEnd() var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, " -- "); - StringAssert.Contains(commandline, $"\"{arg1}\""); - StringAssert.Contains(commandline, $"{arg2}"); + Assert.Contains(" -- ", commandline); + Assert.Contains($"\"{arg1}\"", commandline); + Assert.Contains($"{arg2}", commandline); } [TestMethod] @@ -71,7 +71,7 @@ public void CreateArgumentShouldPassResultsDirectoryCorrectly() var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, $"--resultsDirectory:\"{_vsTestTask.VSTestResultsDirectory?.ItemSpec}\""); + Assert.Contains($"--resultsDirectory:\"{_vsTestTask.VSTestResultsDirectory?.ItemSpec}\"", commandline); } [TestMethod] @@ -82,8 +82,8 @@ public void CreateArgumentShouldNotSetConsoleLoggerVerbosityIfConsoleLoggerIsGiv var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.DoesNotMatch(commandline, new Regex("(--logger:\"Console;Verbosity=normal\")")); - StringAssert.Contains(commandline, "--logger:\"Console;Verbosity=quiet\""); + Assert.DoesNotMatchRegex(new Regex("(--logger:\"Console;Verbosity=normal\")"), commandline); + Assert.Contains("--logger:\"Console;Verbosity=quiet\"", commandline); } [TestMethod] @@ -93,7 +93,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLogger var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=normal"); + Assert.Contains("--logger:Console;Verbosity=normal", commandline); } [TestMethod] @@ -103,7 +103,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLogger var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=normal"); + Assert.Contains("--logger:Console;Verbosity=normal", commandline); } [TestMethod] @@ -113,7 +113,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLogger var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=normal"); + Assert.Contains("--logger:Console;Verbosity=normal", commandline); } [TestMethod] @@ -123,7 +123,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLogger var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=normal"); + Assert.Contains("--logger:Console;Verbosity=normal", commandline); } [TestMethod] @@ -133,7 +133,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLogger var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=normal"); + Assert.Contains("--logger:Console;Verbosity=normal", commandline); } [TestMethod] @@ -143,7 +143,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLogger var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=normal"); + Assert.Contains("--logger:Console;Verbosity=normal", commandline); } [TestMethod] @@ -153,7 +153,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToQuietIfConsoleLoggerI var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=quiet"); + Assert.Contains("--logger:Console;Verbosity=quiet", commandline); } [TestMethod] @@ -163,7 +163,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToQuietIfConsoleLoggerI var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=quiet"); + Assert.Contains("--logger:Console;Verbosity=quiet", commandline); } [TestMethod] @@ -173,7 +173,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToMinimalIfConsoleLogge var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=minimal"); + Assert.Contains("--logger:Console;Verbosity=minimal", commandline); } [TestMethod] @@ -183,7 +183,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToMinimalIfConsoleLogge var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=minimal"); + Assert.Contains("--logger:Console;Verbosity=minimal", commandline); } [TestMethod] @@ -193,7 +193,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToNormalIfConsoleLogger var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=normal"); + Assert.Contains("--logger:Console;Verbosity=normal", commandline); } [TestMethod] @@ -203,7 +203,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToQuietIfConsoleLoggerI var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:Console;Verbosity=quiet"); + Assert.Contains("--logger:Console;Verbosity=quiet", commandline); } [TestMethod] @@ -213,7 +213,7 @@ public void CreateArgumentShouldPreserveWhiteSpaceInLogger() var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:\"trx;LogFileName=foo bar.trx\""); + Assert.Contains("--logger:\"trx;LogFileName=foo bar.trx\"", commandline); } [TestMethod] @@ -226,8 +226,8 @@ public void CreateArgumentShouldAddOneCollectArgumentForEachCollect() var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--collect:name1"); - StringAssert.Contains(commandline, "--collect:\"name 2\""); + Assert.Contains("--collect:name1", commandline); + Assert.Contains("--collect:\"name 2\"", commandline); } [TestMethod] @@ -237,8 +237,8 @@ public void CreateArgumentShouldAddMultipleTestAdapterPaths() var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--testAdapterPath:path1"); - StringAssert.Contains(commandline, "--testAdapterPath:path2"); + Assert.Contains("--testAdapterPath:path1", commandline); + Assert.Contains("--testAdapterPath:path2", commandline); } [TestMethod] @@ -247,8 +247,8 @@ public void CreateArgumentShouldAddMultipleLoggers() _vsTestTask.VSTestLogger = ["trx;LogFileName=foo bar.trx", "console"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--logger:\"trx;LogFileName=foo bar.trx\""); - StringAssert.Contains(commandline, "--logger:console"); + Assert.Contains("--logger:\"trx;LogFileName=foo bar.trx\"", commandline); + Assert.Contains("--logger:console", commandline); } [TestMethod] @@ -261,7 +261,7 @@ public void CreateArgumentShouldAddTraceCollectorDirectoryPathAsTestAdapterForCo var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); string expectedArg = $"--testAdapterPath:\"{_vsTestTask.VSTestTraceDataCollectorDirectoryPath?.ItemSpec}\""; - StringAssert.Contains(commandline, expectedArg); + Assert.Contains(expectedArg, commandline); } [TestMethod] @@ -274,7 +274,7 @@ public void CreateArgumentShouldNotAddTraceCollectorDirectoryPathAsTestAdapterFo var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); string notExpectedArg = $"--testAdapterPath:\"{_vsTestTask.VSTestTraceDataCollectorDirectoryPath?.ItemSpec}\""; - StringAssert.DoesNotMatch(commandline, new Regex(Regex.Escape(notExpectedArg))); + Assert.DoesNotMatchRegex(new Regex(Regex.Escape(notExpectedArg)), commandline); } [TestMethod] @@ -287,7 +287,7 @@ public void CreateArgumentShouldAddTraceCollectorDirectoryPathAsTestAdapterIfSet var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); string expectedArg = $"--testAdapterPath:{_vsTestTask.VSTestTraceDataCollectorDirectoryPath?.ItemSpec}"; - StringAssert.Contains(commandline, expectedArg); + Assert.Contains(expectedArg, commandline); } [TestMethod] @@ -299,7 +299,7 @@ public void CreateArgumentShouldNotAddTestAdapterPathIfVSTestTraceDataCollectorD var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.DoesNotMatch(commandline, new Regex(@"(--testAdapterPath:)")); + Assert.DoesNotMatchRegex(new Regex(@"(--testAdapterPath:)"), commandline); } [TestMethod] @@ -309,6 +309,6 @@ public void CreateArgumentShouldAddNoLogoOptionIfSpecifiedByUser() var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); - StringAssert.Contains(commandline, "--nologo"); + Assert.Contains("--nologo", commandline); } } diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs index 0eb5640f24..fbf6fe4eee 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs @@ -42,6 +42,8 @@ public class DesignModeClientTests private readonly AutoResetEvent _completeEvent; private readonly Mock _mockPlatformEnvironment; + public TestContext TestContext { get; set; } + public DesignModeClientTests() { _mockTestRequestManager = new Mock(); @@ -198,7 +200,7 @@ public void DesignModeClientWithGetTestRunnerProcessStartInfoShouldDeserializeTe // Assert. Assert.IsNotNull(receivedTestRunPayload); Assert.IsNotNull(receivedTestRunPayload.TestCases); - Assert.AreEqual(1, receivedTestRunPayload.TestCases.Count); + Assert.HasCount(1, receivedTestRunPayload.TestCases); // Validate traits var traits = receivedTestRunPayload.TestCases.ToArray()[0].Traits; @@ -259,7 +261,7 @@ public void DesignModeClientWithRunSelectedTestCasesShouldDeserializeTestsWithTr // Assert. Assert.IsNotNull(receivedTestRunPayload); Assert.IsNotNull(receivedTestRunPayload.TestCases); - Assert.AreEqual(1, receivedTestRunPayload.TestCases.Count); + Assert.HasCount(1, receivedTestRunPayload.TestCases); // Validate traits var traits = receivedTestRunPayload.TestCases.ToArray()[0].Traits; @@ -300,7 +302,7 @@ public void DesignModeClientLaunchCustomHostMustReturnIfAckComes() Action sendMessageAction = () => testableDesignModeClient.InvokeCustomHostLaunchAckCallback(expectedProcessId, null); _mockCommunicationManager.Setup(cm => cm.SendMessage(MessageType.CustomTestHostLaunch, It.IsAny())). - Callback(() => Task.Run(sendMessageAction)); + Callback(() => Task.Run(sendMessageAction, TestContext.CancellationToken)); var info = new TestProcessStartInfo(); var processId = testableDesignModeClient.LaunchCustomHost(info, CancellationToken.None); @@ -320,7 +322,7 @@ public void DesignModeClientLaunchCustomHostMustThrowIfInvalidAckComes() _mockCommunicationManager .Setup(cm => cm.SendMessage(MessageType.CustomTestHostLaunch, It.IsAny())) - .Callback(() => Task.Run(sendMessageAction)); + .Callback(() => Task.Run(sendMessageAction, TestContext.CancellationToken)); var info = new TestProcessStartInfo(); Assert.ThrowsExactly(() => testableDesignModeClient.LaunchCustomHost(info, CancellationToken.None)); diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeTestHostLauncherTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeTestHostLauncherTests.cs index 22c33b59bc..876669365d 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeTestHostLauncherTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeTestHostLauncherTests.cs @@ -14,6 +14,8 @@ namespace Microsoft.VisualStudio.TestPlatform.Client.UnitTests.DesignMode; [TestClass] public class DesignModeTestHostLauncherTests { + public TestContext TestContext { get; set; } + [TestMethod] public void DesignModeTestHostLauncherLaunchTestHostShouldCallDesignModeClientToLaunchCustomHost() { @@ -23,7 +25,7 @@ public void DesignModeTestHostLauncherLaunchTestHostShouldCallDesignModeClientTo var testProcessStartInfo = new TestProcessStartInfo(); - launcher.LaunchTestHost(testProcessStartInfo); + launcher.LaunchTestHost(testProcessStartInfo, TestContext.CancellationToken); mockDesignModeClient.Verify(md => md.LaunchCustomHost(testProcessStartInfo, It.IsAny()), Times.Once); } @@ -37,7 +39,7 @@ public void DesignModeDebugTestHostLauncherLaunchTestHostShouldCallDesignModeCli var testProcessStartInfo = new TestProcessStartInfo(); - launcher.LaunchTestHost(testProcessStartInfo); + launcher.LaunchTestHost(testProcessStartInfo, TestContext.CancellationToken); mockDesignModeClient.Verify(md => md.LaunchCustomHost(testProcessStartInfo, It.IsAny()), Times.Once); } diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs index 372d9f1808..a7be4b884e 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs @@ -74,16 +74,9 @@ public void DiscoverAsyncSetsDiscoveryInProgressAndCallManagerToDiscoverTests() public void DiscoveryAsyncIfDiscoverTestsThrowsExceptionSetsDiscoveryInProgressToFalseAndThrowsThatException() { _discoveryManager.Setup(dm => dm.DiscoverTests(_discoveryCriteria, _discoveryRequest as DiscoveryRequest)).Throws(new Exception("DummyException")); - try - { - _discoveryRequest.DiscoverAsync(); - } - catch (Exception ex) - { - Assert.IsTrue(ex is Exception); - Assert.AreEqual("DummyException", ex.Message); - Assert.IsFalse((_discoveryRequest as DiscoveryRequest).DiscoveryInProgress); - } + var ex = Assert.ThrowsExactly(() => _discoveryRequest.DiscoverAsync()); + Assert.AreEqual("DummyException", ex.Message); + Assert.IsFalse((_discoveryRequest as DiscoveryRequest).DiscoveryInProgress); } [TestMethod] @@ -150,7 +143,7 @@ public void HandleDiscoveryCompleteShouldCloseDiscoveryManagerBeforeRaiseDiscove eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), []); - Assert.AreEqual(2, events.Count); + Assert.HasCount(2, events); Assert.AreEqual("close", events[0]); Assert.AreEqual("complete", events[1]); } diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs index d28fa93877..75ec037bf1 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs @@ -34,6 +34,8 @@ public class TestRunRequestTests private readonly Mock _mockDataSerializer; + public TestContext TestContext { get; set; } + public TestRunRequestTests() { _testRunCriteria = new TestRunCriteria(new List { "foo" }, 1); @@ -81,16 +83,10 @@ public void ExecuteAsyncSetsStateToInProgressAndCallManagerToStartTestRun() public void ExecuteAsyncIfStartTestRunThrowsExceptionSetsStateToPendingAndThrowsThatException() { _executionManager.Setup(em => em.StartTestRun(_testRunCriteria, _testRunRequest)).Throws(new Exception("DummyException")); - try - { - _testRunRequest.ExecuteAsync(); - } - catch (Exception ex) - { - Assert.IsTrue(ex is not null); - Assert.AreEqual("DummyException", ex.Message); - Assert.AreEqual(TestRunState.Pending, _testRunRequest.State); - } + var ex = Assert.ThrowsExactly(() => _testRunRequest.ExecuteAsync()); + Assert.IsNotNull(ex); + Assert.AreEqual("DummyException", ex.Message); + Assert.AreEqual(TestRunState.Pending, _testRunRequest.State); } [TestMethod] @@ -585,7 +581,7 @@ public void HandleTestRunCompleteShouldCloseExecutionManager() _testRunRequest.HandleTestRunComplete(new TestRunCompleteEventArgs(new TestRunStatistics(1, null), false, false, null, null, null, TimeSpan.FromSeconds(0)), null, null, null); - Assert.AreEqual(2, events.Count); + Assert.HasCount(2, events); Assert.AreEqual("close", events[0]); Assert.AreEqual("complete", events[1]); } @@ -601,7 +597,9 @@ public void LaunchProcessWithDebuggerAttachedShouldNotCallCustomLauncherIfTestRu var testProcessStartInfo = new TestProcessStartInfo(); _testRunRequest.LaunchProcessWithDebuggerAttached(testProcessStartInfo); +#pragma warning disable MSTEST0049 // Moq Verify pattern - not an actual method invocation mockCustomLauncher.Verify(ml => ml.LaunchTestHost(It.IsAny()), Times.Never); +#pragma warning restore MSTEST0049 } [TestMethod] @@ -617,7 +615,9 @@ public void LaunchProcessWithDebuggerAttachedShouldNotCallCustomLauncherIfLaunch var testProcessStartInfo = new TestProcessStartInfo(); _testRunRequest.LaunchProcessWithDebuggerAttached(testProcessStartInfo); +#pragma warning disable MSTEST0049 // Moq Verify pattern - not an actual method invocation mockCustomLauncher.Verify(ml => ml.LaunchTestHost(It.IsAny()), Times.Never); +#pragma warning restore MSTEST0049 } [TestMethod] @@ -634,7 +634,9 @@ public void LaunchProcessWithDebuggerAttachedShouldCallCustomLauncherIfLauncherI mockCustomLauncher.Setup(ml => ml.IsDebug).Returns(true); _testRunRequest.LaunchProcessWithDebuggerAttached(testProcessStartInfo); +#pragma warning disable MSTEST0049 // Moq Verify pattern - not an actual method invocation mockCustomLauncher.Verify(ml => ml.LaunchTestHost(testProcessStartInfo), Times.Once); +#pragma warning restore MSTEST0049 } /// diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs index a44997fd80..0a4033083a 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs @@ -66,12 +66,14 @@ public void SerialTestRunDecorator_ShouldSerializeTests() Assert.AreEqual(0, Interlocked.Read(ref currentCount)); currentCount = Interlocked.Increment(ref currentCount); TestCase tc = tests!.First(); +#pragma warning disable MSTEST0049 // CancellationToken not relevant in Moq callback Task.Run(() => { Thread.Sleep(100); currentCount = Interlocked.Decrement(ref currentCount); frameworkHandle!.RecordEnd(tc, TestOutcome.Passed); }); +#pragma warning restore MSTEST0049 testCasesRan.Add(tc); }); diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs index f1d12e81c5..295074c4c9 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs @@ -90,7 +90,7 @@ public void UpdateAdditionalExtensionsShouldOnlyAddUniqueExtensionPaths() var updatedExtensions = TestPluginCache.Instance.GetExtensionPaths(string.Empty); Assert.IsNotNull(updatedExtensions); - Assert.AreEqual(1, updatedExtensions.Count); + Assert.ContainsSingle(updatedExtensions); CollectionAssert.AreEqual(new List { additionalExtensions.First() }, updatedExtensions); } @@ -102,7 +102,7 @@ public void UpdateAdditionalExtensionsShouldUpdatePathsThatDoNotExist() var updatedExtensions = TestPluginCache.Instance.GetExtensionPaths(string.Empty); Assert.IsNotNull(updatedExtensions); - Assert.AreEqual(1, updatedExtensions.Count); + Assert.ContainsSingle(updatedExtensions); } [TestMethod] @@ -114,7 +114,7 @@ public void UpdateAdditionalExtensionsShouldUpdateUnfilteredExtensionsListWhenSk // Since the extension is unfiltered, above filter criteria doesn't filter it Assert.IsNotNull(updatedExtensions); - Assert.AreEqual(1, updatedExtensions.Count); + Assert.ContainsSingle(updatedExtensions); } [Ignore] @@ -134,7 +134,7 @@ public void ClearExtensionsShouldClearPathToExtensions() TestPluginCache.Instance.ClearExtensions(); - Assert.AreEqual(0, TestPluginCache.Instance.GetExtensionPaths(string.Empty).Count); + Assert.IsEmpty(TestPluginCache.Instance.GetExtensionPaths(string.Empty)); } #endregion @@ -249,7 +249,7 @@ public void GetDefaultResolutionPathsShouldReturnDirectoryFromDefaultExtensionsP var resolutionPaths = TestPluginCache.Instance.GetDefaultResolutionPaths(); Assert.IsNotNull(resolutionPaths); - Assert.IsTrue(resolutionPaths.Contains(Path.GetDirectoryName(defaultExtensionsFile)!)); + Assert.Contains(Path.GetDirectoryName(defaultExtensionsFile)!, resolutionPaths); } #endregion @@ -298,7 +298,7 @@ public void GetTestExtensionsShouldReturnExtensionsInAssembly() TestPluginCache.Instance.GetTestExtensions(typeof(TestPluginCacheTests).Assembly.Location); Assert.IsNotNull(TestPluginCache.Instance.TestExtensions); - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestDiscoverers!.Count > 0); + Assert.IsNotEmpty(TestPluginCache.Instance.TestExtensions.TestDiscoverers!); } [TestMethod] @@ -352,7 +352,7 @@ public void DiscoverTestExtensionsShouldDiscoverExtensionsFromExtensionsFolder() Assert.IsNotNull(TestPluginCache.Instance.TestExtensions); // Validate the discoverers to be absolutely certain. - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestDiscoverers!.Count > 0); + Assert.IsNotEmpty(TestPluginCache.Instance.TestExtensions.TestDiscoverers!); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs index de46d6098c..ec7e42b5d5 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs @@ -85,7 +85,7 @@ public void GetTestExtensionsInformationShouldReturnLoggerExtensions() var pluginInformation = new TestLoggerPluginInformation(typeof(ValidLogger)); var pluginInformation2 = new TestLoggerPluginInformation(typeof(ValidLogger2)); - Assert.AreEqual(1, testExtensions.Keys.Count(k => k.Contains("csv"))); + Assert.ContainsSingle(testExtensions.Keys.Where(k => k.Contains("csv"))); Assert.IsTrue(testExtensions.ContainsKey(pluginInformation.IdentifierData!)); } @@ -99,9 +99,9 @@ public void GetTestExtensionsInformationShouldReturnDataCollectorExtensionsAndIg var pluginInformation = new DataCollectorConfig(typeof(ValidDataCollector)); - Assert.AreEqual(2, testExtensions.Keys.Count); - Assert.AreEqual(1, testExtensions.Keys.Count(k => k.Equals("datacollector://foo/bar"))); - Assert.AreEqual(1, testExtensions.Keys.Count(k => k.Equals("datacollector://foo/bar1"))); + Assert.HasCount(2, testExtensions.Keys); + Assert.ContainsSingle(testExtensions.Keys.Where(k => k.Equals("datacollector://foo/bar"))); + Assert.ContainsSingle(testExtensions.Keys.Where(k => k.Equals("datacollector://foo/bar1"))); } [TestMethod] @@ -115,7 +115,7 @@ public void GetTestExtensionsInformationShouldReturnSettingsProviderExtensions() var pluginInformation = new TestSettingsProviderPluginInformation(typeof(ValidSettingsProvider)); var pluginInformation2 = new TestSettingsProviderPluginInformation(typeof(ValidSettingsProvider2)); - Assert.IsTrue(testExtensions.Keys.Select(k => k.Contains("ValidSettingsProvider")).Count() >= 3); + Assert.IsGreaterThanOrEqualTo(3, testExtensions.Keys.Select(k => k.Contains("ValidSettingsProvider")).Count()); Assert.IsTrue(testExtensions.ContainsKey(pluginInformation.IdentifierData!)); Assert.IsTrue(testExtensions.ContainsKey(pluginInformation2.IdentifierData!)); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs index a59e6ab3ff..bc690e7297 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs @@ -34,7 +34,7 @@ public void UpdateRunSettingsShouldUpdateGivenSettingsXml() _runSettingsProvider.UpdateRunSettings(runSettingsXml); - StringAssert.Contains(_runSettingsProvider.ActiveRunSettings!.SettingsXml, runSettingsXml); + Assert.Contains(runSettingsXml, _runSettingsProvider.ActiveRunSettings!.SettingsXml!); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestDiscovererPluginInformationTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestDiscovererPluginInformationTests.cs index 6b61aa6568..106bf816ce 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestDiscovererPluginInformationTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestDiscovererPluginInformationTests.cs @@ -37,7 +37,7 @@ public void FileExtensionsShouldReturnEmptyListIfADiscovererSupportsNoFileExtens { _testPluginInformation = new TestDiscovererPluginInformation(typeof(DummyTestDiscovererWithNoFileExtensions)); Assert.IsNotNull(_testPluginInformation.FileExtensions); - Assert.AreEqual(0, _testPluginInformation.FileExtensions.Count); + Assert.IsEmpty(_testPluginInformation.FileExtensions); Assert.IsFalse(_testPluginInformation.IsDirectoryBased); } @@ -142,9 +142,9 @@ public void IsDirectoryBasedShouldReturnTrueIfDiscovererIsDirectoryBased() var testPluginMetada = _testPluginInformation.Metadata.ToArray(); Assert.IsNotNull(_testPluginInformation.FileExtensions); - Assert.AreEqual(0, _testPluginInformation.FileExtensions.Count); + Assert.IsEmpty(_testPluginInformation.FileExtensions); Assert.IsNotNull(testPluginMetada[0]); - Assert.AreEqual(0, ((List)testPluginMetada[0]!).Count); + Assert.IsEmpty((List)testPluginMetada[0]!); Assert.IsTrue(_testPluginInformation.IsDirectoryBased); Assert.IsTrue(bool.Parse(testPluginMetada[3]!.ToString()!)); diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/ConditionTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/ConditionTests.cs index 255a3077d3..02c65418b3 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/ConditionTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/ConditionTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -138,7 +138,7 @@ public void TokenizeConditionShouldHandleEscapedBang() var tokens = Condition.TokenizeFilterConditionString(conditionString).ToArray(); - Assert.AreEqual(3, tokens.Length); + Assert.HasCount(3, tokens); Assert.AreEqual("FullyQualifiedName", tokens[0]); Assert.AreEqual("=", tokens[1]); Assert.AreEqual(@"TestMethod\(""\!""\)", tokens[2]); @@ -151,7 +151,7 @@ public void TokenizeConditionShouldHandleEscapedNotEqual1() var tokens = Condition.TokenizeFilterConditionString(conditionString).ToArray(); - Assert.AreEqual(3, tokens.Length); + Assert.HasCount(3, tokens); Assert.AreEqual("FullyQualifiedName", tokens[0]); Assert.AreEqual("=", tokens[1]); Assert.AreEqual(@"TestMethod\(""\!\=""\)", tokens[2]); @@ -164,7 +164,7 @@ public void TokenizeConditionShouldHandleEscapedNotEqual2() var tokens = Condition.TokenizeFilterConditionString(conditionString).ToArray(); - Assert.AreEqual(3, tokens.Length); + Assert.HasCount(3, tokens); Assert.AreEqual("FullyQualifiedName", tokens[0]); Assert.AreEqual("!=", tokens[1]); Assert.AreEqual(@"TestMethod\(""\!\=""\)", tokens[2]); @@ -177,7 +177,7 @@ public void TokenizeConditionShouldHandleEscapedBackslash() var tokens = Condition.TokenizeFilterConditionString(conditionString).ToArray(); - Assert.AreEqual(3, tokens.Length); + Assert.HasCount(3, tokens); Assert.AreEqual("FullyQualifiedName", tokens[0]); Assert.AreEqual("=", tokens[1]); Assert.AreEqual(@"TestMethod\(""\\""\)", tokens[2]); @@ -190,7 +190,7 @@ public void TokenizeConditionShouldHandleEscapedTilde() var tokens = Condition.TokenizeFilterConditionString(conditionString).ToArray(); - Assert.AreEqual(3, tokens.Length); + Assert.HasCount(3, tokens); Assert.AreEqual("FullyQualifiedName", tokens[0]); Assert.AreEqual("~", tokens[1]); Assert.AreEqual(@"TestMethod\(""\~""\)", tokens[2]); @@ -203,7 +203,7 @@ public void TokenizeConditionShouldHandleEscapedNotTilde() var tokens = Condition.TokenizeFilterConditionString(conditionString).ToArray(); - Assert.AreEqual(3, tokens.Length); + Assert.HasCount(3, tokens); Assert.AreEqual("FullyQualifiedName", tokens[0]); Assert.AreEqual("!~", tokens[1]); Assert.AreEqual(@"TestMethod\(""\!\~""\)", tokens[2]); @@ -216,7 +216,7 @@ public void TokenizeConditionShouldHandleSingleUnescapedBang() var tokens = Condition.TokenizeFilterConditionString(conditionString).ToArray(); - Assert.AreEqual(5, tokens.Length); + Assert.HasCount(5, tokens); Assert.AreEqual("FullyQualifiedName", tokens[0]); Assert.AreEqual("!=", tokens[1]); Assert.AreEqual(@"TestMethod\(""", tokens[2]); @@ -231,7 +231,7 @@ public void TokenizeConditionShouldHandleSingleBangAtEnd() var tokens = Condition.TokenizeFilterConditionString(conditionString).ToArray(); - Assert.AreEqual(2, tokens.Length); + Assert.HasCount(2, tokens); Assert.AreEqual("FullyQualifiedName", tokens[0]); Assert.AreEqual("!", tokens[1]); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FastFilterTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FastFilterTests.cs index 432c7bb6c8..7c1bad5344 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FastFilterTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FastFilterTests.cs @@ -22,7 +22,7 @@ public void MultipleOperatorKindsShouldNotCreateFastFilter() var filterExpressionWrapper = new FilterExpressionWrapper("Name=Test1&(Name=Test2|NameTest3)"); var fastFilter = filterExpressionWrapper.FastFilter; - Assert.IsTrue(fastFilter == null); + Assert.IsNull(fastFilter); } [TestMethod] @@ -31,7 +31,7 @@ public void MultipleOperationKindsShouldNotCreateFastFilter() var filterExpressionWrapper = new FilterExpressionWrapper("Name!=TestClass1&Category=Nightly"); var fastFilter = filterExpressionWrapper.FastFilter; - Assert.IsTrue(fastFilter == null); + Assert.IsNull(fastFilter); } [TestMethod] @@ -40,7 +40,7 @@ public void ContainsOperationShouldNotCreateFastFilter() var filterExpressionWrapper = new FilterExpressionWrapper("Name~TestClass1"); var fastFilter = filterExpressionWrapper.FastFilter; - Assert.IsTrue(fastFilter == null); + Assert.IsNull(fastFilter); } [TestMethod] @@ -49,7 +49,7 @@ public void NotContainsOperationShouldNotCreateFastFilter() var filterExpressionWrapper = new FilterExpressionWrapper("Name!~TestClass1"); var fastFilter = filterExpressionWrapper.FastFilter; - Assert.IsTrue(fastFilter == null); + Assert.IsNull(fastFilter); } [TestMethod] @@ -58,7 +58,7 @@ public void AndOperatorAndEqualsOperationShouldNotCreateFastFilter() var filterExpressionWrapper = new FilterExpressionWrapper("Name=Test1&Name=Test2"); var fastFilter = filterExpressionWrapper.FastFilter; - Assert.IsTrue(fastFilter == null); + Assert.IsNull(fastFilter); Assert.IsTrue(string.IsNullOrEmpty(filterExpressionWrapper.ParseError)); } @@ -68,7 +68,7 @@ public void OrOperatorAndNotEqualsOperationShouldNotCreateFastFilter() var filterExpressionWrapper = new FilterExpressionWrapper("Name!=Test1|Name!=Test2"); var fastFilter = filterExpressionWrapper.FastFilter; - Assert.IsTrue(fastFilter == null); + Assert.IsNull(fastFilter); Assert.IsTrue(string.IsNullOrEmpty(filterExpressionWrapper.ParseError)); } @@ -80,7 +80,7 @@ public void FastFilterWithSingleEqualsClause() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "test1" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("FullyQualifiedName", fastFilter.FilterProperties.Keys.Single()); Assert.IsFalse(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -105,7 +105,7 @@ public void ValidForPropertiesHandlesBigFilteringExpressions() string[]? invalidProperties = filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null); Assert.IsNotNull(invalidProperties); - Assert.AreEqual(1, invalidProperties.Length); + Assert.ContainsSingle(invalidProperties); Assert.AreEqual("Category", invalidProperties[0]); } @@ -131,7 +131,7 @@ public void FastFilterWithMultipleEqualsClause() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "test1", "test2", "test3" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("FullyQualifiedName", fastFilter.FilterProperties.Keys.Single()); Assert.IsFalse(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -152,7 +152,7 @@ public void FastFilterWithMultipleEqualsClauseAndParentheses() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "test1", "test2", "test3" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("FullyQualifiedName", fastFilter.FilterProperties.Keys.Single()); Assert.IsFalse(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -173,7 +173,7 @@ public void FastFilterWithMultipleEqualsClauseAndRegex() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "test1", "test2", "test3" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("FullyQualifiedName", fastFilter.FilterProperties.Keys.Single()); Assert.IsFalse(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -198,7 +198,7 @@ public void FastFilterWithMultipleEqualsClauseForMultiplePropertyValues() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "unittest", "perftest" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("Category", fastFilter.FilterProperties.Keys.Single()); Assert.IsFalse(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -221,7 +221,7 @@ public void FastFilterWithMultipleEqualsClauseAndRegexReplacement() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "testclass.test1", "testclass.test2", "testclass.test3" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("FullyQualifiedName", fastFilter.FilterProperties.Keys.Single()); Assert.IsFalse(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -261,7 +261,7 @@ private static void CheckFastFailureWithNotEqualClause(string filterString) var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "test1" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("FullyQualifiedName", fastFilter.FilterProperties.Keys.Single()); Assert.IsTrue(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -280,7 +280,7 @@ public void FastFilterWithMultipleNotEqualsClause() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "test1", "test2", "test3" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("FullyQualifiedName", fastFilter.FilterProperties.Keys.Single()); Assert.IsTrue(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -301,7 +301,7 @@ public void FastFilterWithMultipleNotEqualsClauseAndRegex() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "test1", "test2", "test3" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("FullyQualifiedName", fastFilter.FilterProperties.Keys.Single()); Assert.IsTrue(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -326,7 +326,7 @@ public void FastFilterWithMultipleNotEqualsClauseForMultiplePropertyValues() var expectedFilterValues = new HashSet(StringComparer.OrdinalIgnoreCase) { "unittest", "perftest" }; - Assert.IsTrue(fastFilter != null); + Assert.IsNotNull(fastFilter); Assert.AreEqual("Category", fastFilter.FilterProperties.Keys.Single()); Assert.IsTrue(fastFilter.IsFilteredOutWhenMatched); Assert.IsTrue(expectedFilterValues.SetEquals(fastFilter.FilterProperties.Values.Single())); @@ -354,15 +354,8 @@ public void FastFilterWithWithRegexParseErrorShouldNotCreateFastFilter() public void FastFilterShouldThrowExceptionForUnsupportedOperatorOperationCombination() { ImmutableHashSet.Builder filterHashSetBuilder = ImmutableHashSet.CreateBuilder(); - try - { - var filter = new FastFilter(ImmutableDictionary.CreateRange(new[] { new KeyValuePair>("dummyName", filterHashSetBuilder.ToImmutableHashSet()) }), Operation.Equal, Operator.And); - } - catch (Exception ex) - { - Assert.IsTrue(ex is ArgumentException); - Assert.AreEqual("An error occurred while creating Fast filter.", ex.Message); - } + var ex = Assert.ThrowsExactly(() => new FastFilter(ImmutableDictionary.CreateRange(new[] { new KeyValuePair>("dummyName", filterHashSetBuilder.ToImmutableHashSet()) }), Operation.Equal, Operator.And)); + Assert.AreEqual("An error occurred while creating Fast filter.", ex.Message); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FilterExpressionTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FilterExpressionTests.cs index feb30519c5..a7d9e9c565 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FilterExpressionTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FilterExpressionTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -26,7 +26,7 @@ public void TokenizeFilterShouldHandleEscapedParenthesis() var tokens = FilterExpression.TokenizeFilterExpressionString(conditionString).ToArray(); - Assert.AreEqual(5, tokens.Length); + Assert.HasCount(5, tokens); Assert.AreEqual("(", tokens[0]); Assert.AreEqual(@"T1\(\) ", tokens[1]); Assert.AreEqual(@"|", tokens[2]); @@ -41,7 +41,7 @@ public void TokenizeFilterShouldHandleEmptyParenthesis() var tokens = FilterExpression.TokenizeFilterExpressionString(conditionString).ToArray(); - Assert.AreEqual(5, tokens.Length); + Assert.HasCount(5, tokens); Assert.AreEqual(" ", tokens[0]); Assert.AreEqual("(", tokens[1]); Assert.AreEqual(" ", tokens[2]); @@ -56,7 +56,7 @@ public void TokenizeFilterShouldHandleEscapedBackslash() var tokens = FilterExpression.TokenizeFilterExpressionString(conditionString).ToArray(); - Assert.AreEqual(5, tokens.Length); + Assert.HasCount(5, tokens); Assert.AreEqual("(", tokens[0]); Assert.AreEqual(@"FQN!=T1\(""\\""\) ", tokens[1]); Assert.AreEqual(@"|", tokens[2]); @@ -71,7 +71,7 @@ public void TokenizeFilterShouldHandleNestedParenthesis() var tokens = FilterExpression.TokenizeFilterExpressionString(conditionString).ToArray(); - Assert.AreEqual(11, tokens.Length); + Assert.HasCount(11, tokens); Assert.AreEqual("(", tokens[0]); Assert.AreEqual("(", tokens[1]); Assert.AreEqual(@"FQN!=T1", tokens[2]); @@ -92,7 +92,7 @@ public void TokenizeFilterShouldHandleInvalidEscapeSequence() var tokens = FilterExpression.TokenizeFilterExpressionString(conditionString).ToArray(); - Assert.AreEqual(5, tokens.Length); + Assert.HasCount(5, tokens); Assert.AreEqual("(", tokens[0]); Assert.AreEqual(@"T1\#\#", tokens[1]); Assert.AreEqual(@")", tokens[2]); diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsTests.cs index f1ad362808..0c3193067f 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsTests.cs @@ -54,7 +54,7 @@ public void LoadSettingsXmlShoulLoadAndInitializeSettingsXml() var expectedRunSettings = "" + Environment.NewLine + ""; - StringAssert.Contains(runSettings.SettingsXml, expectedRunSettings); + Assert.Contains(expectedRunSettings, runSettings.SettingsXml!); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/SettingsProvider/SettingsProviderExtensionManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/SettingsProvider/SettingsProviderExtensionManagerTests.cs index 515017cd51..a776b5fb58 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/SettingsProvider/SettingsProviderExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/SettingsProvider/SettingsProviderExtensionManagerTests.cs @@ -82,7 +82,7 @@ public void CreateShouldDiscoverSettingsProviderExtensions() var extensionManager = SettingsProviderExtensionManager.Create(); Assert.IsNotNull(extensionManager.SettingsProvidersMap); - Assert.IsTrue(extensionManager.SettingsProvidersMap.Count > 0); + Assert.IsNotEmpty(extensionManager.SettingsProvidersMap); } [TestMethod] @@ -94,7 +94,7 @@ public void CreateShouldCacheDiscoveredExtensions() SettingsProviderExtensionManager.Create(); Assert.IsNotNull(extensionManager.SettingsProvidersMap); - Assert.IsTrue(extensionManager.SettingsProvidersMap.Count > 0); + Assert.IsNotEmpty(extensionManager.SettingsProvidersMap); } #endregion diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/SourceNavigationParserTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/SourceNavigationParserTests.cs index 2f144c2971..b79dd36747 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/SourceNavigationParserTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/SourceNavigationParserTests.cs @@ -26,7 +26,7 @@ public void FindMethodLocations_ReturnsSignatureAndBodyStartLines() var result = SourceNavigationParser.FindMethodLocations(lines, "MyMethod"); - Assert.AreEqual(1, result.Count); + Assert.ContainsSingle(result); Assert.AreEqual(4, result[0].SignatureLine); // 1-based: " public void MyMethod()" Assert.AreEqual(5, result[0].BodyStartLine); // 1-based: " {" } @@ -50,7 +50,7 @@ public void FindMethodLocations_OverloadedMethods() var result = SourceNavigationParser.FindMethodLocations(lines, "OverLoaded"); - Assert.AreEqual(2, result.Count); + Assert.HasCount(2, result); Assert.AreEqual(3, result[0].SignatureLine); Assert.AreEqual(4, result[0].BodyStartLine); Assert.AreEqual(7, result[1].SignatureLine); @@ -73,7 +73,7 @@ public void FindMethodBodyStartLines_SimpleMethod() var result = SourceNavigationParser.FindMethodBodyStartLines(lines, "MyMethod"); - Assert.AreEqual(1, result.Count); + Assert.ContainsSingle(result); Assert.AreEqual(4, result[0]); // 1-based: line " {" } @@ -94,7 +94,7 @@ public void FindMethodBodyStartLines_MethodWithAttribute() var result = SourceNavigationParser.FindMethodBodyStartLines(lines, "PassTestMethod1"); - Assert.AreEqual(1, result.Count); + Assert.ContainsSingle(result); Assert.AreEqual(5, result[0]); // 1-based: line " {" } @@ -112,7 +112,7 @@ public void FindMethodBodyStartLines_BraceOnSameLineAsSignature() var result = SourceNavigationParser.FindMethodBodyStartLines(lines, "Inline"); - Assert.AreEqual(1, result.Count); + Assert.ContainsSingle(result); Assert.AreEqual(3, result[0]); // 1-based: brace is on same line as signature } @@ -135,7 +135,7 @@ public void FindMethodBodyStartLines_OverloadedMethods() var result = SourceNavigationParser.FindMethodBodyStartLines(lines, "OverLoaded"); - Assert.AreEqual(2, result.Count); + Assert.HasCount(2, result); Assert.AreEqual(4, result[0]); // first overload brace Assert.AreEqual(8, result[1]); // second overload brace } @@ -155,7 +155,7 @@ public void FindMethodBodyStartLines_MethodNotFound() var result = SourceNavigationParser.FindMethodBodyStartLines(lines, "NotExist"); - Assert.AreEqual(0, result.Count); + Assert.IsEmpty(result); } [TestMethod] @@ -173,7 +173,7 @@ public void FindMethodBodyStartLines_DoesNotMatchPropertyOrField() // "MyMethod" followed by ' =' should not match (no '(' after name). var result = SourceNavigationParser.FindMethodBodyStartLines(lines, "MyMethod"); - Assert.AreEqual(0, result.Count); + Assert.IsEmpty(result); } [TestMethod] @@ -192,7 +192,7 @@ public void FindMethodBodyStartLines_AsyncMethod() var result = SourceNavigationParser.FindMethodBodyStartLines(lines, "AsyncTestMethod"); - Assert.AreEqual(1, result.Count); + Assert.ContainsSingle(result); Assert.AreEqual(4, result[0]); } @@ -235,7 +235,7 @@ public void FindMethodBodyStartLines_RealSimpleClassLibrary() Assert.AreEqual(15, SourceNavigationParser.FindMethodBodyStartLines(lines, "AsyncTestMethod")[0]); var overloads = SourceNavigationParser.FindMethodBodyStartLines(lines, "OverLoadedMethod"); - Assert.AreEqual(2, overloads.Count); + Assert.HasCount(2, overloads); Assert.AreEqual(20, overloads[0]); Assert.AreEqual(24, overloads[1]); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Telemetry/MetricsCollectionTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Telemetry/MetricsCollectionTests.cs index 2f0e02dfed..d3d2a0258e 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Telemetry/MetricsCollectionTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Telemetry/MetricsCollectionTests.cs @@ -47,7 +47,7 @@ public void MetricsShouldReturnValidMetricsIfValidItemsAreThere() _metricsCollection.Add("DummyMessage", "DummyValue"); _metricsCollection.Add("DummyMessage2", "DummyValue"); - Assert.AreEqual(2, _metricsCollection.Metrics.Count); + Assert.HasCount(2, _metricsCollection.Metrics); Assert.IsTrue(_metricsCollection.Metrics.ContainsKey("DummyMessage")); Assert.IsTrue(_metricsCollection.Metrics.ContainsKey("DummyMessage2")); } @@ -55,6 +55,6 @@ public void MetricsShouldReturnValidMetricsIfValidItemsAreThere() [TestMethod] public void MetricsShouldReturnEmptyDictionaryIfMetricsIsEmpty() { - Assert.AreEqual(0, _metricsCollection.Metrics.Count); + Assert.IsEmpty(_metricsCollection.Metrics); } } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/ExceptionUtilitiesTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/ExceptionUtilitiesTests.cs index 13864a9ab4..0747ee1caa 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/ExceptionUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/ExceptionUtilitiesTests.cs @@ -32,18 +32,18 @@ public void GetExceptionMessageShouldReturnExceptionMessageContainingAllExceptio var exception = new ArgumentException("Some bad stuff", innerException2); var message = ExceptionUtilities.GetExceptionMessage(exception); - StringAssert.Contains(message, exception.Message); - StringAssert.Contains(message, innerException.Message); - StringAssert.Contains(message, innerException.Message); + Assert.Contains(exception.Message, message); + Assert.Contains(innerException.Message, message); + Assert.Contains(innerException.Message, message); } [TestMethod] public void GetExceptionMessageShouldReturnExceptionMessageContainingStackTrace() { var message = ExceptionUtilities.GetExceptionMessage(GetExceptionWithStackTrace()); - StringAssert.Contains(message, "Stack trace:"); + Assert.Contains("Stack trace:", message); // this test is where it or - StringAssert.Contains(message, "ExceptionUtilitiesTests.GetExceptionWithStackTrace"); + Assert.Contains("ExceptionUtilitiesTests.GetExceptionWithStackTrace", message); } private static Exception GetExceptionWithStackTrace() diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketClientTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketClientTests.cs index d15d378d31..4942ca2412 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketClientTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketClientTests.cs @@ -24,6 +24,8 @@ public class SocketClientTests : SocketTestsBase, IDisposable private TcpClient? _tcpClient; + public TestContext TestContext { get; set; } + public SocketClientTests() { _socketClient = new SocketClient(); @@ -49,8 +51,10 @@ public void SocketClientStartShouldConnectToLoopbackOnGivenPort() _socketClient.Start(connectionInfo); +#pragma warning disable MSTEST0049 // AcceptTcpClientAsync(CancellationToken) unavailable on .NET Framework var acceptClientTask = _tcpListener.AcceptTcpClientAsync(); Assert.IsTrue(acceptClientTask.Wait(Timeout)); +#pragma warning restore MSTEST0049 Assert.IsTrue(acceptClientTask.Result.Connected); } @@ -142,8 +146,10 @@ public void SocketClientStopShouldCloseChannel() var connectionInfo = StartLocalServer(); _socketClient.Start(connectionInfo); +#pragma warning disable MSTEST0049 // Use 'TestContext.CancellationToken' - AcceptTcpClientAsync/Wait overloads unavailable on .NET Framework var acceptClientTask = _tcpListener.AcceptTcpClientAsync(); if (acceptClientTask.Wait(TimeSpan.FromMilliseconds(1000))) +#pragma warning restore MSTEST0049 { _tcpClient = acceptClientTask.Result; waitEvent.WaitOne(1000); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs index 727f6943c6..aeb0d0337e 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs @@ -5,7 +5,6 @@ using System.IO; using System.Net; using System.Net.Sockets; -using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -16,6 +15,10 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; +// ConnectAsync(IPAddress, int, CancellationToken) and AcceptTcpClientAsync(CancellationToken) +// overloads are unavailable on .NET Framework; suppress CancellationToken usage warnings. +#pragma warning disable MSTEST0049 // Use 'TestContext.CancellationToken' + namespace Microsoft.TestPlatform.CommunicationUtilities.PlatformTests; [TestClass] @@ -33,6 +36,8 @@ public class SocketCommunicationManagerTests : IDisposable private readonly TcpClient _tcpClient; private readonly TcpListener _tcpListener; + public TestContext TestContext { get; set; } + public SocketCommunicationManagerTests() { _communicationManager = new SocketCommunicationManager(); @@ -57,7 +62,7 @@ public async Task HostServerShouldStartServerAndReturnPortNumber() { var port = _communicationManager.HostServer(new IPEndPoint(IPAddress.Loopback, 0)).Port; - Assert.IsTrue(port > 0); + Assert.IsGreaterThan(0, port); await _tcpClient.ConnectAsync(IPAddress.Loopback, port); Assert.IsTrue(_tcpClient.Connected); } @@ -75,7 +80,8 @@ public async Task AcceptClientAsyncShouldWaitForClientConnection() clientConnected = true; waitEvent.Set(); }, - null); + null, + TestContext.CancellationToken); await _tcpClient.ConnectAsync(IPAddress.Loopback, port); Assert.IsTrue(_tcpClient.Connected); @@ -156,14 +162,9 @@ public void WaitForServerConnectionShouldReturnFalseIfClientIsNotConnected() } [TestMethod] + [OSCondition(OperatingSystems.Windows | OperatingSystems.Linux)] public async Task StopClientShouldDisconnectClient() { - // TODO: This won't throw on MacOS? No way to try it. - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return; - } - var client = await StartServerAndWaitForConnection(); _communicationManager.StopClient(); @@ -283,8 +284,8 @@ public void SocketPollShouldNotHangServerClientCommunication() var client = new SocketCommunicationManager(); int port = server.HostServer(new IPEndPoint(IPAddress.Loopback, 0)).Port; - client.SetupClientAsync(new IPEndPoint(IPAddress.Loopback, port)).Wait(); - server.AcceptClientAsync().Wait(); + client.SetupClientAsync(new IPEndPoint(IPAddress.Loopback, port)).Wait(TestContext.CancellationToken); + server.AcceptClientAsync().Wait(TestContext.CancellationToken); server.WaitForClientConnection(1000); client.WaitForServerConnection(1000); @@ -296,7 +297,7 @@ public void SocketPollShouldNotHangServerClientCommunication() while (dataReceived < 2048 * 5) { dataReceived += server.ReceiveRawMessageAsync(CancellationToken.None).Result!.Length; - Task.Delay(1000).Wait(); + Task.Delay(1000, TestContext.CancellationToken).Wait(TestContext.CancellationToken); } clientThread.Join(); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketServerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketServerTests.cs index 326d598adc..764d80099d 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketServerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketServerTests.cs @@ -23,6 +23,8 @@ public class SocketServerTests : SocketTestsBase, IDisposable private readonly string _defaultConnection = IPAddress.Loopback.ToString() + ":0"; private readonly ICommunicationEndPoint _socketServer; + public TestContext TestContext { get; set; } + public SocketServerTests() { _socketServer = new SocketServer(); @@ -109,7 +111,7 @@ public void SocketServerStopShouldCloseChannel() _socketServer.Stop(); - waitEvent.Wait(); + waitEvent.Wait(TestContext.CancellationToken); Assert.ThrowsExactly(() => channel!.Send(Dummydata)); } @@ -170,6 +172,8 @@ public async Task SocketEndpointShouldInitializeChannelOnServerConnection() private async Task ConnectToServer(int port) { +#pragma warning disable MSTEST0049 // Use 'TestContext.CancellationToken' - ConnectAsync CancellationToken overload unavailable on .NET Framework await _tcpClient.ConnectAsync(IPAddress.Loopback, port); +#pragma warning restore MSTEST0049 } } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs index 8646240817..d33c3aaf90 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs @@ -244,7 +244,7 @@ public void ProcessRequestsShouldAddSourceDirectoryToTestPluginCache() _requestHandler.ProcessRequests(); _mockFileHelper.Verify(x => x.EnumerateFiles($@"{temp}dir1", SearchOption.AllDirectories, @"Collector.dll"), Times.Once); - Assert.IsTrue(TestPluginCache.Instance.GetExtensionPaths(@"Collector.dll").Contains(Path.Combine(temp, "dir1", "abc.DataCollector.dll"))); + Assert.Contains(Path.Combine(temp, "dir1", "abc.DataCollector.dll"), TestPluginCache.Instance.GetExtensionPaths(@"Collector.dll")); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs index 311230f716..3c16b43f17 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs @@ -55,14 +55,14 @@ public void SendAfterTestRunEndAndGetResultShouldReturnAttachments() Assert.IsNotNull(result.AttachmentSets); Assert.IsNotNull(result.AttachmentSets); Assert.IsNotNull(result.Metrics); - Assert.AreEqual(1, result.AttachmentSets.Count); - Assert.AreEqual(1, result.InvokedDataCollectors!.Count); - Assert.AreEqual(0, result.Metrics.Count); + Assert.HasCount(1, result.AttachmentSets); + Assert.HasCount(1, result.InvokedDataCollectors!); + Assert.IsEmpty(result.Metrics); Assert.IsNotNull(result.AttachmentSets[0]); Assert.AreEqual(displayName, result.AttachmentSets[0].DisplayName); Assert.AreEqual(datacollectorUri, result.AttachmentSets[0].Uri); Assert.AreEqual(attachmentUri, result.AttachmentSets[0].Attachments[0].Uri); - Assert.IsNotNull(result.InvokedDataCollectors[0]); + Assert.IsNotNull(result.InvokedDataCollectors![0]); Assert.AreEqual(datacollectorUri, result.InvokedDataCollectors[0].Uri); Assert.AreEqual(invokedDataCollector.FilePath, result.InvokedDataCollectors[0].FilePath); Assert.AreEqual(invokedDataCollector.AssemblyQualifiedName, result.InvokedDataCollectors[0].AssemblyQualifiedName); @@ -92,14 +92,14 @@ public void SendAfterTestRunEndAndGetResultShouldReturnAttachmentsAndPropagateTe Assert.IsNotNull(result.AttachmentSets); Assert.IsNotNull(result.AttachmentSets); Assert.IsNotNull(result.Metrics); - Assert.AreEqual(1, result.AttachmentSets.Count); - Assert.AreEqual(1, result.InvokedDataCollectors!.Count); - Assert.AreEqual(0, result.Metrics.Count); + Assert.HasCount(1, result.AttachmentSets); + Assert.HasCount(1, result.InvokedDataCollectors!); + Assert.IsEmpty(result.Metrics); Assert.IsNotNull(result.AttachmentSets[0]); Assert.AreEqual(displayName, result.AttachmentSets[0].DisplayName); Assert.AreEqual(datacollectorUri, result.AttachmentSets[0].Uri); Assert.AreEqual(attachmentUri, result.AttachmentSets[0].Attachments[0].Uri); - Assert.IsNotNull(result.InvokedDataCollectors[0]); + Assert.IsNotNull(result.InvokedDataCollectors![0]); Assert.AreEqual(datacollectorUri, result.InvokedDataCollectors[0].Uri); Assert.AreEqual(invokedDataCollector.FilePath, result.InvokedDataCollectors[0].FilePath); Assert.AreEqual(invokedDataCollector.AssemblyQualifiedName, result.InvokedDataCollectors[0].AssemblyQualifiedName); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestCaseSerializationTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestCaseSerializationTests.cs index 6205d5b415..f1daf13268 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestCaseSerializationTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestCaseSerializationTests.cs @@ -247,7 +247,7 @@ public void TestCaseObjectShouldDeserializeTraitsWithSpecialCharacters(int versi var test = Deserialize(json, version); var traits = test.Traits.ToArray(); - Assert.AreEqual(1, traits.Length); + Assert.HasCount(1, traits); Assert.AreEqual(@"SDJDDHW>,:&^%//\\\\", traits[0].Value); } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestObjectConverterTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestObjectConverterTests.cs index 90b10ef588..d1ebb2aaa7 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestObjectConverterTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestObjectConverterTests.cs @@ -91,7 +91,7 @@ public void TestObjectShouldDeserializeCustomProperties() var test = Deserialize(json); var properties = test.Properties.ToArray(); - Assert.AreEqual(2, properties.Length); + Assert.HasCount(2, properties); Assert.AreEqual(Guid.Parse("02048dfd-3da7-475d-a011-8dd1121855ec"), test.GetPropertyValue(properties.First(x => x.Label == "label1"))); Assert.AreEqual(29, test.GetPropertyValue(properties.First(x => x.Label == "label2"))); } @@ -104,7 +104,7 @@ public void TestObjectShouldDeserializeNullValueForProperty() var test = Deserialize(json); var properties = test.Properties.ToArray(); - Assert.AreEqual(1, properties.Length); + Assert.HasCount(1, properties); Assert.IsTrue(string.IsNullOrEmpty(test.GetPropertyValue(properties[0])!.ToString())); } @@ -116,7 +116,7 @@ public void TestObjectShouldDeserializeStringArrayValueForProperty() var test = Deserialize(json); var properties = test.Properties.ToArray(); - Assert.AreEqual(1, properties.Length); + Assert.HasCount(1, properties); CollectionAssert.AreEqual(new[] { "val1", "val2" }, (string[])test.GetPropertyValue(properties[0])!); } @@ -128,7 +128,7 @@ public void TestObjectShouldDeserializeDatetimeOffset() var test = Deserialize(json); var properties = test.Properties.ToArray(); - Assert.AreEqual(1, properties.Length); + Assert.HasCount(1, properties); Assert.AreEqual(DateTimeOffset.MaxValue, test.GetPropertyValue(properties[0])); } @@ -160,7 +160,7 @@ public void TestObjectSetPropertyValueShouldNotConvertIfValueMatchesPropertyData // type is object testobj.SetPropertyValue(property, false); - Assert.AreEqual(false, testobj.GetPropertyValue(property)); + Assert.IsFalse((bool)testobj.GetPropertyValue(property)!); } private static string Serialize(T data) diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestResultSerializationTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestResultSerializationTests.cs index 58e9aaa9d0..f98cc9d60d 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestResultSerializationTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestResultSerializationTests.cs @@ -78,8 +78,8 @@ public void TestResultObjectShouldContainAllPropertiesOnDeserialization(int vers var test = Deserialize(json, version); Assert.AreEqual(TestResult.TestCase.Id, test.TestCase.Id); - Assert.AreEqual(TestResult.Attachments.Count, test.Attachments.Count); - Assert.AreEqual(TestResult.Messages.Count, test.Messages.Count); + Assert.HasCount(TestResult.Attachments.Count, test.Attachments); + Assert.HasCount(TestResult.Messages.Count, test.Messages); Assert.AreEqual(TestResult.ComputerName, test.ComputerName); Assert.AreEqual(TestResult.DisplayName, test.DisplayName); @@ -116,7 +116,7 @@ public void TestResultObjectShouldDeserializeAttachments(int version) var result = Deserialize(json, version); - Assert.AreEqual(1, result.Attachments.Count); + Assert.HasCount(1, result.Attachments); Assert.AreEqual(new Uri("http://dummyUri"), result.Attachments[0].Uri); Assert.AreEqual("sampleAttachment", result.Attachments[0].DisplayName); } @@ -147,8 +147,8 @@ public void TestResultObjectShouldDeserializeDefaultValues(int version) var result = Deserialize(json, version); - Assert.AreEqual(0, result.Attachments.Count); - Assert.AreEqual(0, result.Messages.Count); + Assert.IsEmpty(result.Attachments); + Assert.IsEmpty(result.Messages); Assert.IsNull(result.DisplayName); Assert.IsNull(result.ErrorMessage); Assert.IsNull(result.ErrorStackTrace); @@ -216,8 +216,8 @@ public void TestResultObjectShouldContainAllPropertiesOnDeserializationV2(int ve var test = Deserialize(json, version); Assert.AreEqual(TestResult.TestCase.Id, test.TestCase.Id); - Assert.AreEqual(TestResult.Attachments.Count, test.Attachments.Count); - Assert.AreEqual(TestResult.Messages.Count, test.Messages.Count); + Assert.HasCount(TestResult.Attachments.Count, test.Attachments); + Assert.HasCount(TestResult.Messages.Count, test.Messages); Assert.AreEqual(TestResult.ComputerName, test.ComputerName); Assert.AreEqual(TestResult.DisplayName, test.DisplayName); @@ -254,7 +254,7 @@ public void TestResultObjectShouldDeserializeAttachmentsV2(int version) var result = Deserialize(json, version); - Assert.AreEqual(1, result.Attachments.Count); + Assert.HasCount(1, result.Attachments); Assert.AreEqual(new Uri("http://dummyUri"), result.Attachments[0].Uri); Assert.AreEqual("sampleAttachment", result.Attachments[0].DisplayName); } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/SocketCommunicationManagerTest.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/SocketCommunicationManagerTest.cs index c8faff459a..27e3190f54 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/SocketCommunicationManagerTest.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/SocketCommunicationManagerTest.cs @@ -5,7 +5,6 @@ namespace Microsoft.TestPlatform.CommunicationUtilities.UnitTests; -[TestClass] -public class SocketCommunicationManagerTest +public static class SocketCommunicationManagerTest { } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs index fbd2727f5a..f1df84a12d 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs @@ -43,6 +43,8 @@ public class TestRequestSenderTests private readonly ITestRequestSender _testRequestSender; private ConnectedEventArgs _connectedEventArgs; + public TestContext TestContext { get; set; } = null!; + public TestRequestSenderTests() { _connectionInfo = new TestHostConnectionInfo @@ -104,7 +106,7 @@ public void WaitForRequestHandlerConnectionWithTimeoutShouldReturnImmediatelyWhe watch.Stop(); Assert.IsFalse(connected); - Assert.IsTrue(watch.ElapsedMilliseconds < connectionTimeout); + Assert.IsLessThan(connectionTimeout, watch.ElapsedMilliseconds); } [TestMethod] @@ -119,7 +121,7 @@ public void WaitForRequestHandlerConnectionWithTimeoutShouldReturnImmediatelyIfH watch.Stop(); Assert.IsFalse(connected); - Assert.IsTrue(watch.ElapsedMilliseconds < connectionTimeout); + Assert.IsLessThan(connectionTimeout, watch.ElapsedMilliseconds); } [TestMethod] @@ -793,8 +795,8 @@ public async Task StartTestRunWithTestsShouldNotifyExecutionCompleteIfClientDisc SetupFakeCommunicationChannel(); // Note: Even if the calls get invoked on separate threads, the request sender should send back the complete message just once. - var t1 = Task.Run(RaiseClientDisconnectedEvent); - var t2 = Task.Run(() => _testRequestSender.StartTestRun(runCriteria, _mockExecutionEventsHandler.Object)); + var t1 = Task.Run(RaiseClientDisconnectedEvent, TestContext.CancellationToken); + var t2 = Task.Run(() => _testRequestSender.StartTestRun(runCriteria, _mockExecutionEventsHandler.Object), TestContext.CancellationToken); await Task.WhenAll(t1, t2); diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs index 1b7ec113d6..053ae7d3a2 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs @@ -29,14 +29,14 @@ public void GetArgumentsDictionaryShouldIgnoreValuesWithoutPreceedingHypen() var args = new List() { "port", "12312", "--parentprocessid", "2312", "--testsourcepath", @"C:\temp\1.dll" }; var argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(args.ToArray()); - Assert.IsTrue(argsDictionary.Count == 2); + Assert.HasCount(2, argsDictionary); Assert.AreEqual("2312", argsDictionary["--parentprocessid"]); Assert.AreEqual(@"C:\temp\1.dll", argsDictionary["--testsourcepath"]); args = ["--port", "12312", "--parentprocessid", "2312", "testsourcepath", @"C:\temp\1.dll"]; argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(args.ToArray()); - Assert.IsTrue(argsDictionary.Count == 2); + Assert.HasCount(2, argsDictionary); Assert.AreEqual("12312", argsDictionary["--port"]); Assert.AreEqual("2312", argsDictionary["--parentprocessid"]); } @@ -59,7 +59,7 @@ public void GetStringArgFromDictShouldReturnNullIfValueIsNotPresent() string? data = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, "--hello"); - Assert.IsTrue(argsDictionary.Count == 2); + Assert.HasCount(2, argsDictionary); Assert.IsNull(data); } @@ -71,7 +71,7 @@ public void GetStringArgFromDictShouldReturnEmptyStringIfKeyIsNotPresent() string? data = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, "--port"); - Assert.IsTrue(argsDictionary.Count == 2); + Assert.HasCount(2, argsDictionary); Assert.AreEqual(string.Empty, data); } @@ -79,10 +79,10 @@ public void GetStringArgFromDictShouldReturnEmptyStringIfKeyIsNotPresent() public void GetArgumentsDictionaryShouldReturnEmptyDictionaryIfEmptyArgIsPassed() { var argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(null); - Assert.IsTrue(argsDictionary.Count == 0); + Assert.IsEmpty(argsDictionary); argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary([]); - Assert.IsTrue(argsDictionary.Count == 0); + Assert.IsEmpty(argsDictionary); } [TestMethod] @@ -91,7 +91,7 @@ public void GetArgumentsDictionaryShouldTreatValueAsNullIfTwoConsecutiveKeysAreP var args = new List() { "--hello", "--world" }; var argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(args.ToArray()); - Assert.IsTrue(argsDictionary.Count == 2); + Assert.HasCount(2, argsDictionary); Assert.IsNull(argsDictionary["--hello"]); Assert.IsNull(argsDictionary["--world"]); } diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Output/OutputExtensionsTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Output/OutputExtensionsTests.cs index 59a8006b64..7c8d403833 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Output/OutputExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Output/OutputExtensionsTests.cs @@ -64,7 +64,7 @@ public void OutputErrorForSimpleMessageShouldSetConsoleColorToRed() } _mockOutput.Object.Error(false, "HelloError", null); - Assert.IsTrue(_color == ConsoleColor.Red, "Console color not set."); + Assert.AreEqual(ConsoleColor.Red, _color, "Console color not set."); } [TestMethod] @@ -90,7 +90,7 @@ public void OutputWarningForSimpleMessageShouldSetConsoleColorToYellow() } _mockOutput.Object.Warning(false, "HelloWarning", null); - Assert.IsTrue(_color == ConsoleColor.Yellow); + Assert.AreEqual(ConsoleColor.Yellow, _color); } [TestMethod] @@ -116,7 +116,7 @@ public void OutputInformationForSimpleMessageShouldSetConsoleColorToGivenColor() } _mockOutput.Object.Information(false, ConsoleColor.Green, "HelloInformation", null); - Assert.IsTrue(_color == ConsoleColor.Green); + Assert.AreEqual(ConsoleColor.Green, _color); } [TestMethod] @@ -139,7 +139,7 @@ public void OutputInformationShouldNotChangeConsoleOutputColor() _mockOutput.Object.Information(false, "HelloInformation {0} {1}", "Foo", "Bar"); _mockOutput.Verify(o => o.WriteLine("HelloInformation Foo Bar", OutputLevel.Information), Times.Once()); - Assert.IsTrue(color1 == color2); + Assert.AreEqual(color2, color1); } private bool CanNotSetConsoleForegroundColor() diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs index 4f5ffd888f..a9f52f2b1b 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs @@ -109,7 +109,7 @@ public void TraceShouldWriteWarning() EqtTrace.TraceLevel = PlatformTraceLevel.Warning; #endif EqtTrace.Warning("Dummy Warning Message"); - Assert.IsTrue(ReadLogFile().Contains("Dummy Warning Message"), "Expected Warning message"); + Assert.Contains("Dummy Warning Message", ReadLogFile(), "Expected Warning message"); } [TestMethod] @@ -121,7 +121,7 @@ public void TraceShouldWriteVerbose() EqtTrace.TraceLevel = PlatformTraceLevel.Verbose; #endif EqtTrace.Verbose("Dummy Verbose Message"); - Assert.IsTrue(ReadLogFile().Contains("Dummy Verbose Message"), "Expected Verbose message"); + Assert.Contains("Dummy Verbose Message", ReadLogFile(), "Expected Verbose message"); } [TestMethod] @@ -133,7 +133,7 @@ public void TraceShouldWriteInfo() EqtTrace.TraceLevel = PlatformTraceLevel.Info; #endif EqtTrace.Info("Dummy Info Message"); - Assert.IsTrue(ReadLogFile().Contains("Dummy Info Message"), "Expected Info message"); + Assert.Contains("Dummy Info Message", ReadLogFile(), "Expected Info message"); } [TestMethod] @@ -148,8 +148,8 @@ public void TraceShouldNotWriteVerboseIfTraceLevelIsInfo() EqtTrace.Verbose("Unexpected Dummy Verbose Message"); var logFileContent = ReadLogFile(); - Assert.IsFalse(logFileContent.Contains("Unexpected Dummy Verbose Message"), "Verbose message not expected"); - Assert.IsTrue(logFileContent.Contains("Dummy Info Message"), "Expected Info message"); + Assert.DoesNotContain("Unexpected Dummy Verbose Message", logFileContent, "Verbose message not expected"); + Assert.Contains("Dummy Info Message", logFileContent, "Expected Info message"); } [TestMethod] @@ -162,7 +162,7 @@ public void TraceShouldNotWriteIfDoNotInitializationIsSetToTrue() EqtTrace.TraceLevel = PlatformTraceLevel.Info; #endif EqtTrace.Info("Dummy Info Message: TraceShouldNotWriteIfDoNotInitializationIsSetToTrue"); - Assert.IsFalse(ReadLogFile().Contains("Dummy Info Message: TraceShouldNotWriteIfDoNotInitializationIsSetToTrue"), "Did not expect Dummy Info message"); + Assert.DoesNotContain("Dummy Info Message: TraceShouldNotWriteIfDoNotInitializationIsSetToTrue", ReadLogFile(), "Did not expect Dummy Info message"); } private static string ReadLogFile() diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs index b546de29ea..3e35169852 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs @@ -141,12 +141,12 @@ public void OncePausedNoFurtherJobsAreProcessedUntilResumeIsCalled() // Allow other threads to execute and verify no jobs processed because the queue is paused. Thread.Sleep(0); - Assert.AreEqual(0, processedJobs.Count); + Assert.IsEmpty(processedJobs); queue.Resume(); } - Assert.AreEqual(3, processedJobs.Count); + Assert.HasCount(3, processedJobs); } [TestMethod] @@ -360,7 +360,7 @@ public void TestLargeTestResultCanBeLoadedWithBlockingEnabled() } [TestMethod] - [Timeout(60000)] + [Timeout(60000, CooperativeCancellation = true)] public void TestDisposeUnblocksBlockedThreads() { var allowJobProcessingHandlerToProceed = new ManualResetEvent(false); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Adapter/FrameworkHandleTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Adapter/FrameworkHandleTests.cs index 0d521d7e5a..381c4ec991 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Adapter/FrameworkHandleTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Adapter/FrameworkHandleTests.cs @@ -54,18 +54,8 @@ public void LaunchProcessWithDebuggerAttachedShouldThrowIfNotInDebugContext() var tec = GetTestExecutionContext(); var frameworkHandle = new FrameworkHandle(null, new TestRunCache(100, TimeSpan.MaxValue, (s, r, ip) => { }), tec, null!); - var isExceptionThrown = false; - try - { - frameworkHandle.LaunchProcessWithDebuggerAttached(null!, null, null, null); - } - catch (InvalidOperationException exception) - { - isExceptionThrown = true; - Assert.AreEqual("This operation is not allowed in the context of a non-debug run.", exception.Message); - } - - Assert.IsTrue(isExceptionThrown); + var exception = Assert.ThrowsExactly(() => frameworkHandle.LaunchProcessWithDebuggerAttached(null!, null, null, null)); + Assert.AreEqual("This operation is not allowed in the context of a non-debug run.", exception.Message); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Adapter/TestExecutionRecorderTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Adapter/TestExecutionRecorderTests.cs index be223b219a..cce3ab3ad1 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Adapter/TestExecutionRecorderTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Adapter/TestExecutionRecorderTests.cs @@ -43,28 +43,28 @@ public void AttachmentsShouldReturnEmptyListByDefault() var attachments = _testRecorder.Attachments; Assert.IsNotNull(attachments); - Assert.AreEqual(0, attachments.Count); + Assert.IsEmpty(attachments); } [TestMethod] public void RecordStartShouldUpdateTestRunCache() { _testRecorder.RecordStart(_testCase); - Assert.IsTrue(_testableTestRunCache.TestStartedList.Contains(_testCase)); + Assert.Contains(_testCase, _testableTestRunCache.TestStartedList); } [TestMethod] public void RecordResultShouldUpdateTestRunCache() { _testRecorder.RecordResult(_testResult); - Assert.IsTrue(_testableTestRunCache.TestResultList.Contains(_testResult)); + Assert.Contains(_testResult, _testableTestRunCache.TestResultList); } [TestMethod] public void RecordEndShouldUpdateTestRunCache() { _testRecorder.RecordEnd(_testCase, TestOutcome.Passed); - Assert.IsTrue(_testableTestRunCache.TestCompletedList.Contains(_testCase)); + Assert.Contains(_testCase, _testableTestRunCache.TestCompletedList); } [TestMethod] @@ -193,7 +193,7 @@ public void RecordResultShouldFlushIfRecordEndWasCalledBefore() _testRecorderWithTestEventsHandler.RecordResult(_testResult); _mockTestCaseEventsHandler.Verify(x => x.SendTestCaseEnd(_testCase, TestOutcome.Passed), Times.Once); - Assert.IsTrue(_testableTestRunCache.TestResultList.Contains(_testResult)); + Assert.Contains(_testResult, _testableTestRunCache.TestResultList); } [TestMethod] @@ -205,7 +205,7 @@ public void RecordResultShouldSendTestCaseEndEventAndFlushIfRecordEndWasCalledAf _testRecorderWithTestEventsHandler.RecordEnd(_testCase, _testResult.Outcome); _mockTestCaseEventsHandler.Verify(x => x.SendTestCaseEnd(_testCase, TestOutcome.Passed), Times.Once); - Assert.IsTrue(_testableTestRunCache.TestResultList.Contains(_testResult)); + Assert.Contains(_testResult, _testableTestRunCache.TestResultList); } [TestMethod] @@ -216,7 +216,7 @@ public void RecordResultShouldSendTestCaseEndEventIfRecordEndWasNotCalled() _testRecorderWithTestEventsHandler.RecordResult(_testResult); _mockTestCaseEventsHandler.Verify(x => x.SendTestCaseEnd(_testCase, TestOutcome.Passed), Times.Once); - Assert.IsTrue(_testableTestRunCache.TestResultList.Contains(_testResult)); + Assert.Contains(_testResult, _testableTestRunCache.TestResultList); } #endregion diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs index f41d35a55c..9be5f13b50 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK @@ -95,7 +95,7 @@ public async Task DataCollectorAttachmentProcessorAppDomain_ShouldReturnCorrectA Assert.AreEqual(attachmentSet.DisplayName, firstAttachmentSet.DisplayName); Assert.AreEqual(attachmentSet.Uri, firstAttachmentSet.Uri); - Assert.AreEqual(attachmentSet.Attachments.Count, attachmentsResult.Count); + Assert.HasCount(attachmentSet.Attachments.Count, attachmentsResult); Assert.AreEqual(attachmentSet.Attachments[0].Description, firstAttachmentSet.Attachments[0].Description); Assert.AreEqual(attachmentSet.Attachments[0].Uri, firstAttachmentSet.Attachments[0].Uri); Assert.AreEqual(attachmentSet.Attachments[0].Uri, firstAttachmentSet.Attachments[0].Uri); @@ -158,7 +158,7 @@ public async Task DataCollectorAttachmentProcessorAppDomain_ShouldLogCorrectly() // assert countdownEvent.Wait(new CancellationTokenSource(10000).Token); - Assert.AreEqual(3, messages.Count); + Assert.HasCount(3, messages); Assert.AreEqual(TestMessageLevel.Informational, messages[0].Item1); Assert.AreEqual("Info", messages[0].Item2); Assert.AreEqual(TestMessageLevel.Warning, messages[1].Item1); @@ -183,7 +183,7 @@ public void DataCollectorAttachmentProcessorAppDomain_ShouldReportFailureDuringE { if (messageLevel == TestMessageLevel.Error) { - Assert.IsTrue(message.Contains("System.Exception: Failed to create the extension")); + Assert.Contains("System.Exception: Failed to create the extension", message); errorReportEvent.Set(); } }); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs index e9a7008106..3aa33d6b01 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs @@ -1,6 +1,8 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable MSTEST0049 // CancellationToken not applicable in test setup/Moq callbacks + using System; using System.Collections.Generic; using System.Linq; @@ -100,7 +102,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnNoAttachments_IfNoA var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); // assert - Assert.AreEqual(0, result.Count); + Assert.IsEmpty(result); _mockAttachmentHandler1.Verify(h => h.GetExtensionUris(), Times.Never); _mockAttachmentHandler2.Verify(h => h.GetExtensionUris(), Times.Never); _mockAttachmentHandler1.Verify(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Never); @@ -140,8 +142,8 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttach var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); // assert - Assert.AreEqual(1, result.Count); - Assert.IsTrue(result.Contains(inputAttachments[0])); + Assert.ContainsSingle(result); + Assert.Contains(inputAttachments[0], result); _mockAttachmentHandler1.Verify(h => h.GetExtensionUris()); _mockAttachmentHandler2.Verify(h => h.GetExtensionUris()); _mockAttachmentHandler1.Verify(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Never); @@ -189,8 +191,8 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachmen var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); // assert - Assert.AreEqual(1, result.Count); - Assert.IsTrue(result.Contains(outputAttachments[0])); + Assert.ContainsSingle(result); + Assert.Contains(outputAttachments[0], result); _mockEventSource.Verify(s => s.TestRunAttachmentsProcessingStart(1)); _mockEventSource.Verify(s => s.TestRunAttachmentsProcessingStop(1)); _mockAttachmentHandler1.Verify(h => h.GetExtensionUris()); @@ -237,8 +239,8 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); // assert - Assert.AreEqual(1, result.Count); - Assert.IsTrue(result.Contains(inputAttachments[0])); + Assert.ContainsSingle(result); + Assert.Contains(inputAttachments[0], result); _mockAttachmentHandler1.Verify(h => h.GetExtensionUris()); _mockAttachmentHandler2.Verify(h => h.GetExtensionUris(), Times.Once); _mockAttachmentHandler1.Verify(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.Is>(c => c.Count == 1 && c.Contains(inputAttachments[0])), It.IsAny>(), It.IsAny(), _cancellationTokenSource.Token)); @@ -279,8 +281,8 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); // assert - Assert.AreEqual(1, result.Count); - Assert.IsTrue(result.Contains(inputAttachments[0])); + Assert.ContainsSingle(result); + Assert.Contains(inputAttachments[0], result); _mockAttachmentHandler1.Verify(h => h.GetExtensionUris(), Times.Never); _mockAttachmentHandler2.Verify(h => h.GetExtensionUris(), Times.Never); _mockAttachmentHandler1.Verify(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Never); @@ -348,10 +350,10 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachment var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); // assert - Assert.AreEqual(3, result.Count); - Assert.IsTrue(result.Contains(inputAttachments[4])); - Assert.IsTrue(result.Contains(outputAttachmentsForHandler1[0])); - Assert.IsTrue(result.Contains(outputAttachmentsForHandler2[0])); + Assert.HasCount(3, result); + Assert.Contains(inputAttachments[4], result); + Assert.Contains(outputAttachmentsForHandler1[0], result); + Assert.Contains(outputAttachmentsForHandler2[0], result); _mockAttachmentHandler1.Verify(h => h.GetExtensionUris()); _mockAttachmentHandler2.Verify(h => h.GetExtensionUris()); _mockAttachmentHandler1.Verify(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.Is>(c => c.Count == 2 && c.Contains(inputAttachments[0]) && c.Contains(inputAttachments[1])), It.IsAny>(), It.IsAny(), _cancellationTokenSource.Token)); @@ -489,8 +491,8 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ // assert Assert.IsNotNull(result); - Assert.AreEqual(1, result.Count); - Assert.IsTrue(result.Contains(inputAttachments[0])); + Assert.ContainsSingle(result); + Assert.Contains(inputAttachments[0], result); _mockAttachmentHandler1.Verify(h => h.GetExtensionUris()); _mockAttachmentHandler2.Verify(h => h.GetExtensionUris(), Times.Never); _mockAttachmentHandler1.Verify(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.Is>(c => c.Count == 1 && c.Contains(inputAttachments[0])), It.IsAny>(), It.IsAny(), _cancellationTokenSource.Token)); @@ -703,8 +705,8 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldNotConsumeAttachmentsIfPr { // assert Assert.IsTrue(firstProcessorFailed); - Assert.AreEqual(1, i1.Count); - Assert.AreEqual(3, i1.Single().Attachments.Count); + Assert.ContainsSingle(i1); + Assert.HasCount(3, i1.Single().Attachments); for (int i = 0; i < i1.Single().Attachments.Count; i++) { Assert.AreEqual(inputAttachments.Single().Attachments[i], i1.Single().Attachments[i]); @@ -761,8 +763,8 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldNotConsumeAttachmentsIfAl { // assert Assert.IsTrue(firstProcessorFailed); - Assert.AreEqual(1, i1.Count); - Assert.AreEqual(3, i1.Single().Attachments.Count); + Assert.ContainsSingle(i1); + Assert.HasCount(3, i1.Single().Attachments); for (int i = 0; i < i1.Single().Attachments.Count; i++) { Assert.AreEqual(inputAttachments.Single().Attachments[i], i1.Single().Attachments[i]); @@ -834,7 +836,7 @@ private static bool VerifyProgressArgs(TestRunAttachmentsProcessingProgressEvent { Assert.AreEqual(1, args.CurrentAttachmentProcessorIndex); Assert.AreEqual(2, args.AttachmentProcessorsCount); - Assert.AreEqual(1, args.CurrentAttachmentProcessorUris.Count); + Assert.ContainsSingle(args.CurrentAttachmentProcessorUris); Assert.AreEqual(Uri1, args.CurrentAttachmentProcessorUris.First().AbsoluteUri); return progress == args.CurrentAttachmentProcessorProgress; } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/DiscoveryDataAggregatorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/DiscoveryDataAggregatorTests.cs index b3a85e0ada..25633d4687 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/DiscoveryDataAggregatorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/DiscoveryDataAggregatorTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -57,7 +57,7 @@ public void AggregateDiscoveryDataMetricsShouldAggregateMetricsCorrectly() aggregator.AggregateMetrics(null); var runMetrics = aggregator.GetMetrics(); - Assert.AreEqual(0, runMetrics.Count); + Assert.IsEmpty(runMetrics); } [TestMethod] @@ -161,7 +161,7 @@ public void GetAggregatedDiscoveryDataMetricsShouldReturnEmptyIfMetricAggregator aggregator.AggregateMetrics(new Dictionary()); var runMetrics = aggregator.GetMetrics(); - Assert.AreEqual(0, runMetrics.Count); + Assert.IsEmpty(runMetrics); } [TestMethod] @@ -172,7 +172,7 @@ public void GetAggregatedDiscoveryDataMetricsShouldReturnEmptyIfMetricsIsNull() aggregator.AggregateMetrics(null); var runMetrics = aggregator.GetMetrics(); - Assert.AreEqual(0, runMetrics.Count); + Assert.IsEmpty(runMetrics); } [TestMethod] @@ -248,9 +248,9 @@ public void MarkSourcesWithStatusWhenSourcesIsNullDoesNothing(DiscoveryStatus di dataAggregator.MarkSourcesWithStatus(null, discoveryStatus); // Assert - Assert.AreEqual(0, dataAggregator.GetSourcesWithStatus(DiscoveryStatus.FullyDiscovered).Count); - Assert.AreEqual(0, dataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered).Count); - Assert.AreEqual(0, dataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered).Count); + Assert.IsEmpty(dataAggregator.GetSourcesWithStatus(DiscoveryStatus.FullyDiscovered)); + Assert.IsEmpty(dataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered)); + Assert.IsEmpty(dataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered)); } [TestMethod] @@ -264,7 +264,7 @@ public void MarkSourcesWithStatusIgnoresNullSources(DiscoveryStatus discoverySta var sources = new[] { "a", null, "b" }; // Sanity check - Assert.AreEqual(0, dataAggregator.GetSourcesWithStatus(discoveryStatus).Count); + Assert.IsEmpty(dataAggregator.GetSourcesWithStatus(discoveryStatus)); // Act dataAggregator.MarkSourcesWithStatus(sources, discoveryStatus); @@ -363,7 +363,7 @@ public void MarkSourcesBasedOnDiscoveredTestCasesReuseLastDiscoveredSource() public void GetSourcesWithStatusWhenEmptyDictionaryReturnsEmptyList(DiscoveryStatus discoveryStatus) { var instanceSources = new DiscoveryDataAggregator().GetSourcesWithStatus(discoveryStatus); - Assert.AreEqual(0, instanceSources.Count); + Assert.IsEmpty(instanceSources); } [TestMethod] @@ -423,6 +423,6 @@ public void TryAggregateIsMessageSentOnlyReportsOnceEvenWhenRunningInParallel() System.Threading.Tasks.Parallel.For(0, 100, _ => concurrentBag.Add(dataAggregator.TryAggregateIsMessageSent())); // Assert - Assert.AreEqual(1, concurrentBag.Count(b => b)); + Assert.ContainsSingle(concurrentBag.Where(b => b)); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelOperationManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelOperationManagerTests.cs index c188beffcb..039bcbb479 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelOperationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelOperationManagerTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable MSTEST0049 // CancellationToken not applicable in test setup/Moq callbacks + using System; using System.Collections.Generic; using System.Linq; diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs index e67d96da49..c5cb74955a 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs @@ -1,6 +1,8 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable MSTEST0049 // CancellationToken not applicable in test setup/Moq callbacks + using System; using System.Collections.Generic; using System.Threading; @@ -113,7 +115,7 @@ public void AbortShouldCallAllConcurrentManagersOnce() parallelDiscoveryManager.Abort(); - Assert.AreEqual(2, _usedMockManagers.Count, "Number of Concurrent Managers created should be equal to the number of sources that should run"); + Assert.HasCount(2, _usedMockManagers, "Number of Concurrent Managers created should be equal to the number of sources that should run"); _usedMockManagers.ForEach(dm => dm.Verify(m => m.Abort(), Times.Once)); } @@ -141,7 +143,7 @@ public void DiscoverTestsShouldProcessAllSources() } Assert.IsTrue(discoveryCompleted, "Test discovery not completed."); - Assert.AreEqual(_sources.Count, _processedSources.Count, "All Sources must be processed."); + Assert.HasCount(_sources.Count, _processedSources, "All Sources must be processed."); AssertMissingAndDuplicateSources(_processedSources); } @@ -214,7 +216,7 @@ public void DiscoveryTestsShouldStopDiscoveryIfAbortionWasRequested() }); Assert.IsTrue(_discoveryCompleted.Wait(Timeout10Seconds), "Test discovery not completed."); - Assert.AreEqual(1, _processedSources.Count, "One source should be processed."); + Assert.ContainsSingle(_processedSources, "One source should be processed."); } [TestMethod] @@ -232,7 +234,7 @@ public void DiscoveryTestsShouldStopDiscoveryIfAbortionWithEventHandlerWasReques }); Assert.IsTrue(_discoveryCompleted.Wait(Timeout10Seconds), "Test discovery not completed."); - Assert.AreEqual(1, _processedSources.Count, "One source should be processed."); + Assert.ContainsSingle(_processedSources, "One source should be processed."); } [TestMethod] @@ -252,7 +254,7 @@ public void DiscoveryTestsShouldProcessAllSourceIfOneDiscoveryManagerIsStarved() // Processed sources should be 1 since the 2nd source is never discovered Assert.IsTrue(_discoveryCompleted.Wait(Timeout10Seconds), "Test discovery not completed."); - Assert.AreEqual(1, _processedSources.Count, "All Sources must be processed."); + Assert.ContainsSingle(_processedSources, "All Sources must be processed."); } [TestMethod] @@ -324,10 +326,10 @@ public void DiscoveryTestsWithCompletionMarksAllSourcesAsFullyDiscovered() Task.Run(() => parallelDiscoveryManager.DiscoverTests(_discoveryCriteriaWith2Sources, _mockEventHandler.Object)); Assert.IsTrue(_discoveryCompleted.Wait(Timeout10Seconds), "Test discovery not completed."); - Assert.AreEqual(_sources.Count, _processedSources.Count, "All Sources must be processed."); + Assert.HasCount(_sources.Count, _processedSources, "All Sources must be processed."); CollectionAssert.AreEquivalent(_sources, _dataAggregator.GetSourcesWithStatus(DiscoveryStatus.FullyDiscovered)); - Assert.AreEqual(0, _dataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered).Count); - Assert.AreEqual(0, _dataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered).Count); + Assert.IsEmpty(_dataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered)); + Assert.IsEmpty(_dataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered)); } private ParallelProxyDiscoveryManager SetupDiscoveryManager(Func getProxyManager, int parallelLevel, bool abortDiscovery) @@ -401,7 +403,7 @@ private void InvokeAndVerifyInitialize(int maxParallelLevel, bool skipDefaultAda parallelDiscoveryManager.Initialize(skipDefaultAdapters); // Verify - Assert.AreEqual(0, _usedMockManagers.Count, $"No managers are pre-created until there is work for them."); + Assert.IsEmpty(_usedMockManagers, $"No managers are pre-created until there is work for them."); _usedMockManagers.ForEach(dm => dm.Verify(m => m.Initialize(skipDefaultAdapters), Times.Once)); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs index ea9cf8f8db..cab7a938ef 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable MSTEST0049 // CancellationToken not applicable in test setup/Moq callbacks + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -117,7 +119,7 @@ public void AbortShouldCallAllConcurrentManagersOnce() parallelExecutionManager.StartTestRun(_testRunCriteriaWith2Sources, new Mock().Object); parallelExecutionManager.Abort(It.IsAny()); - Assert.AreEqual(2, _usedMockManagers.Count, "Number of Concurrent Managers created should be equal to the amount of dlls that run"); + Assert.HasCount(2, _usedMockManagers, "Number of Concurrent Managers created should be equal to the amount of dlls that run"); _usedMockManagers.ForEach(em => em.Verify(m => m.Abort(It.IsAny()), Times.Once)); } @@ -130,7 +132,7 @@ public void CancelShouldCallAllConcurrentManagersOnce() parallelExecutionManager.StartTestRun(_testRunCriteriaWith2Sources, new Mock().Object); parallelExecutionManager.Cancel(It.IsAny()); - Assert.AreEqual(2, _usedMockManagers.Count, "Number of Concurrent Managers created should be equal to the amount of dlls that run"); + Assert.HasCount(2, _usedMockManagers, "Number of Concurrent Managers created should be equal to the amount of dlls that run"); _usedMockManagers.ForEach(em => em.Verify(m => m.Cancel(It.IsAny()), Times.Once)); } @@ -142,7 +144,7 @@ public void StartTestRunShouldProcessAllSources() parallelExecutionManager.StartTestRun(_testRunCriteriaWith2Sources, _mockEventHandler.Object); Assert.IsTrue(_executionCompleted.Wait(Timeout3Seconds), "Test run not completed."); - Assert.AreEqual(_sources.Count, _processedSources.Count, "All Sources must be processed."); + Assert.HasCount(_sources.Count, _processedSources, "All Sources must be processed."); AssertMissingAndDuplicateSources(_processedSources); } @@ -156,7 +158,7 @@ public void StartTestRunShouldProcessAllTestCases() parallelExecutionManager.StartTestRun(_testRunCriteriaWithTestsFrom3Dlls, _mockEventHandler.Object); Assert.IsTrue(_executionCompleted.Wait(Timeout3Seconds), "Test run not completed."); - Assert.AreEqual(_testCases.Count, _processedTestCases.Count, "All Tests must be processed."); + Assert.HasCount(_testCases.Count, _processedTestCases, "All Tests must be processed."); AssertMissingAndDuplicateTestCases(_testCases, _processedTestCases); } @@ -168,7 +170,7 @@ public void StartTestRunWithSourcesShouldNotSendCompleteUntilAllSourcesAreProces Task.Run(() => parallelExecutionManager.StartTestRun(_testRunCriteriaWith2Sources, _mockEventHandler.Object)); Assert.IsTrue(_executionCompleted.Wait(Timeout3Seconds), "Test run not completed."); - Assert.AreEqual(_sources.Count, _processedSources.Count, "All Sources must be processed."); + Assert.HasCount(_sources.Count, _processedSources, "All Sources must be processed."); AssertMissingAndDuplicateSources(_processedSources); } @@ -236,7 +238,7 @@ public void StartTestRunWithTestsShouldNotSendCompleteUntilAllTestsAreProcessed( } Assert.IsTrue(executionCompleted, "Test run not completed."); - Assert.AreEqual(_testCases.Count, _processedTestCases.Count, "All Tests must be processed."); + Assert.HasCount(_testCases.Count, _processedTestCases, "All Tests must be processed."); AssertMissingAndDuplicateTestCases(_testCases, _processedTestCases); } @@ -252,7 +254,7 @@ public void StartTestRunShouldNotProcessAllSourcesOnExecutionCancelsForAnySource Task.Run(() => parallelExecutionManager.StartTestRun(_testRunCriteriaWith2Sources, _mockEventHandler.Object)); Assert.IsTrue(_executionCompleted.Wait(Timeout3Seconds), "Test run not completed."); - Assert.AreEqual(1, _processedSources.Count, "Abort should stop all sources execution."); + Assert.ContainsSingle(_processedSources, "Abort should stop all sources execution."); } [TestMethod] @@ -268,7 +270,7 @@ public void StartTestRunShouldNotProcessAllSourcesOnExecutionAborted() Task.Run(() => parallelExecutionManager.StartTestRun(_testRunCriteriaWith2Sources, _mockEventHandler.Object)); Assert.IsTrue(_executionCompleted.Wait(Timeout3Seconds), "Test run not completed."); - Assert.AreEqual(1, _processedSources.Count, "Abort should stop all sources execution."); + Assert.ContainsSingle(_processedSources, "Abort should stop all sources execution."); } [TestMethod] @@ -284,7 +286,7 @@ public void StartTestRunShouldProcessAllSourcesOnExecutionAbortsForAnySource() Assert.IsTrue(_executionCompleted.Wait(Timeout3Seconds), "Test run not completed."); - Assert.AreEqual(2, _processedSources.Count, "Abort should stop all sources execution."); + Assert.HasCount(2, _processedSources, "Abort should stop all sources execution."); } [TestMethod] @@ -301,7 +303,7 @@ public void StartTestRunShouldProcessAllSourceIfOneDiscoveryManagerIsStarved() // Processed sources should be 1 since the 2nd source is never discovered Assert.IsTrue(_executionCompleted.Wait(Timeout3Seconds), "Test run not completed."); - Assert.AreEqual(1, _processedSources.Count, "All Sources must be processed."); + Assert.ContainsSingle(_processedSources, "All Sources must be processed."); } [TestMethod] @@ -392,9 +394,9 @@ public void StartTestRunShouldAggregateRunData() { Assert.AreEqual(TimeSpan.FromMilliseconds(200), completeArgs.ElapsedTimeInRunningTests, "Time should be max of all"); - Assert.AreEqual(2, completeArgs.AttachmentSets.Count, + Assert.HasCount(2, completeArgs.AttachmentSets, "All Complete Arg attachments should return"); - Assert.AreEqual(2, runAttachments.Count, "All RunContextAttachments should return"); + Assert.HasCount(2, runAttachments, "All RunContextAttachments should return"); Assert.IsTrue(completeArgs.IsAborted, "Aborted value must be OR of all values"); Assert.IsTrue(completeArgs.IsCanceled, "Canceled value must be OR of all values"); @@ -423,7 +425,7 @@ public void StartTestRunShouldAggregateRunData() Assert.IsTrue(_executionCompleted.Wait(Timeout3Seconds), "Test run not completed."); Assert.IsNull(assertException, assertException?.ToString()); - Assert.AreEqual(_sources.Count, _processedSources.Count, "All Sources must be processed."); + Assert.HasCount(_sources.Count, _processedSources, "All Sources must be processed."); AssertMissingAndDuplicateSources(_processedSources); } @@ -575,7 +577,7 @@ private void InvokeAndVerifyInitialize(int parallelLevel, bool skipDefaultAdapte parallelExecutionManager.Initialize(skipDefaultAdapters); - Assert.AreEqual(0, _usedMockManagers.Count, $"No concurrent managers should be pre-created, until there is work for them"); + Assert.IsEmpty(_usedMockManagers, $"No concurrent managers should be pre-created, until there is work for them"); _usedMockManagers.ForEach(em => em.Verify(m => m.Initialize(skipDefaultAdapters), Times.Once)); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs index 17ddab5c74..ebee92ba21 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#pragma warning disable MSTEST0049 // CancellationToken not applicable in test setup/Moq callbacks + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -32,10 +34,10 @@ public void ParallelRunDataAggregatorConstructorShouldInitializeAggregatorVars() Assert.IsNotNull(aggregator.RunCompleteArgsAttachments, "RunCompleteArgsAttachments list must not be null"); Assert.IsNotNull(aggregator.RunContextAttachments, "RunContextAttachments list must not be null"); - Assert.AreEqual(0, aggregator.Exceptions.Count, "Exceptions List must be initialized as empty list."); - Assert.AreEqual(0, aggregator.ExecutorUris.Count, "Exceptions List must be initialized as empty list."); - Assert.AreEqual(0, aggregator.RunCompleteArgsAttachments.Count, "RunCompleteArgsAttachments List must be initialized as empty list."); - Assert.AreEqual(0, aggregator.RunContextAttachments.Count, "RunContextAttachments List must be initialized as empty list"); + Assert.IsEmpty(aggregator.Exceptions, "Exceptions List must be initialized as empty list."); + Assert.IsEmpty(aggregator.ExecutorUris, "Exceptions List must be initialized as empty list."); + Assert.IsEmpty(aggregator.RunCompleteArgsAttachments, "RunCompleteArgsAttachments List must be initialized as empty list."); + Assert.IsEmpty(aggregator.RunContextAttachments, "RunContextAttachments List must be initialized as empty list"); Assert.IsFalse(aggregator.IsAborted, "Aborted must be false by default"); @@ -55,7 +57,7 @@ public void AggregateShouldAggregateRunCompleteAttachmentsCorrectly() aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, attachmentSet1, null, null); - Assert.AreEqual(1, aggregator.RunCompleteArgsAttachments.Count, "RunCompleteArgsAttachments List must have data."); + Assert.ContainsSingle(aggregator.RunCompleteArgsAttachments, "RunCompleteArgsAttachments List must have data."); var attachmentSet2 = new Collection { @@ -64,7 +66,7 @@ public void AggregateShouldAggregateRunCompleteAttachmentsCorrectly() aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, attachmentSet2, null, null); - Assert.AreEqual(2, aggregator.RunCompleteArgsAttachments.Count, "RunCompleteArgsAttachments List must have aggregated data."); + Assert.HasCount(2, aggregator.RunCompleteArgsAttachments, "RunCompleteArgsAttachments List must have aggregated data."); } [TestMethod] @@ -79,7 +81,7 @@ public void AggregateShouldAggregateRunContextAttachmentsCorrectly() aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, attachmentSet1, null, null, null); - Assert.AreEqual(1, aggregator.RunContextAttachments.Count, "RunContextAttachments List must have data."); + Assert.ContainsSingle(aggregator.RunContextAttachments, "RunContextAttachments List must have data."); var attachmentSet2 = new Collection { @@ -88,7 +90,7 @@ public void AggregateShouldAggregateRunContextAttachmentsCorrectly() aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, attachmentSet2, null, null, null); - Assert.AreEqual(2, aggregator.RunContextAttachments.Count, "RunContextAttachments List must have aggregated data."); + Assert.HasCount(2, aggregator.RunContextAttachments, "RunContextAttachments List must have aggregated data."); } [TestMethod] @@ -101,19 +103,19 @@ public void AggregateShouldAggregateInvokedCollectorsCorrectly() new(new Uri("datacollector://sample"),"sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location,false) }; aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, null, invokedDataCollectors, null); - Assert.AreEqual(1, aggregator.InvokedDataCollectors.Count, "InvokedDataCollectors List must have data."); + Assert.ContainsSingle(aggregator.InvokedDataCollectors, "InvokedDataCollectors List must have data."); var invokedDataCollectors2 = new Collection() { new(new Uri("datacollector://sample2"),"sample2", typeof(int).AssemblyQualifiedName!, typeof(int).Assembly.Location,false) }; aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, null, invokedDataCollectors2, null); - Assert.AreEqual(2, aggregator.InvokedDataCollectors.Count, "InvokedDataCollectors List must have aggregated data."); + Assert.HasCount(2, aggregator.InvokedDataCollectors, "InvokedDataCollectors List must have aggregated data."); aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, null, invokedDataCollectors, null); aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, null, invokedDataCollectors2, null); - Assert.AreEqual(2, aggregator.InvokedDataCollectors.Count, "InvokedDataCollectors List must have aggregated data."); + Assert.HasCount(2, aggregator.InvokedDataCollectors, "InvokedDataCollectors List must have aggregated data."); Assert.AreEqual(invokedDataCollectors[0].AssemblyQualifiedName, aggregator.InvokedDataCollectors[0].AssemblyQualifiedName); Assert.AreEqual(invokedDataCollectors[0].FilePath, aggregator.InvokedDataCollectors[0].FilePath); Assert.AreEqual(invokedDataCollectors[0].Uri, aggregator.InvokedDataCollectors[0].Uri); @@ -201,7 +203,7 @@ public void AggregateShouldAggregateExceptionsCorrectly() var aggregatedException = aggregator.GetAggregatedException() as AggregateException; Assert.IsNotNull(aggregatedException, "Aggregated exception must NOT be null"); Assert.IsNotNull(aggregatedException.InnerExceptions, "Inner exception list must NOT be null"); - Assert.AreEqual(1, aggregatedException.InnerExceptions.Count, "Inner exception list must have one element"); + Assert.ContainsSingle(aggregatedException.InnerExceptions, "Inner exception list must have one element"); Assert.AreEqual(exception1, aggregatedException.InnerExceptions[0], "Inner exception must be the one set."); var exception2 = new NotSupportedException(); @@ -211,7 +213,7 @@ public void AggregateShouldAggregateExceptionsCorrectly() aggregatedException = aggregator.GetAggregatedException() as AggregateException; Assert.IsNotNull(aggregatedException, "Aggregated exception must NOT be null"); Assert.IsNotNull(aggregatedException.InnerExceptions, "Inner exception list must NOT be null"); - Assert.AreEqual(2, aggregatedException.InnerExceptions.Count, "Inner exception list must have one element"); + Assert.HasCount(2, aggregatedException.InnerExceptions, "Inner exception list must have one element"); Assert.AreEqual(exception2, aggregatedException.InnerExceptions[1], "Inner exception must be the one set."); } @@ -222,19 +224,19 @@ public void AggregateShouldAggregateExecutorUrisCorrectly() aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, null, null, null); - Assert.AreEqual(0, aggregator.ExecutorUris.Count, "ExecutorUris List must not have data."); + Assert.IsEmpty(aggregator.ExecutorUris, "ExecutorUris List must not have data."); var uri1 = "x://hello1"; aggregator.Aggregate(null, new List() { uri1 }, null, TimeSpan.Zero, false, false, null, null, null, null); - Assert.AreEqual(1, aggregator.ExecutorUris.Count, "ExecutorUris List must have data."); - Assert.IsTrue(aggregator.ExecutorUris.Contains(uri1), "ExecutorUris List must have correct data."); + Assert.ContainsSingle(aggregator.ExecutorUris, "ExecutorUris List must have data."); + Assert.Contains(uri1, aggregator.ExecutorUris, "ExecutorUris List must have correct data."); var uri2 = "x://hello2"; aggregator.Aggregate(null, new List() { uri2 }, null, TimeSpan.Zero, false, false, null, null, null, null); - Assert.AreEqual(2, aggregator.ExecutorUris.Count, "ExecutorUris List must have aggregated data."); - Assert.IsTrue(aggregator.ExecutorUris.Contains(uri2), "ExecutorUris List must have correct data."); + Assert.HasCount(2, aggregator.ExecutorUris, "ExecutorUris List must have aggregated data."); + Assert.Contains(uri2, aggregator.ExecutorUris, "ExecutorUris List must have correct data."); } [TestMethod] @@ -295,7 +297,7 @@ public void AggregateRunDataMetricsShouldAggregateMetricsCorrectly() aggregator.AggregateRunDataMetrics(null); var runMetrics = aggregator.GetAggregatedRunDataMetrics(); - Assert.AreEqual(0, runMetrics.Count); + Assert.IsEmpty(runMetrics); } [TestMethod] @@ -382,7 +384,7 @@ public void GetAggregatedRunDataMetricsShouldReturnEmptyIfMetricAggregatorIsEmpt aggregator.AggregateRunDataMetrics(dict); var runMetrics = aggregator.GetAggregatedRunDataMetrics(); - Assert.AreEqual(0, runMetrics.Count); + Assert.IsEmpty(runMetrics); } [TestMethod] @@ -394,7 +396,7 @@ public void GetAggregatedRunDataMetricsShouldReturnEmptyIfMetricsIsNull() aggregator.AggregateRunDataMetrics(null); var runMetrics = aggregator.GetAggregatedRunDataMetrics(); - Assert.AreEqual(0, runMetrics.Count); + Assert.IsEmpty(runMetrics); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs index f9483d82bb..c3c01e6be3 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs @@ -22,7 +22,6 @@ namespace TestPlatform.CrossPlatEngine.UnitTests.Client; -[TestClass] public class ProxyBaseManagerTests { private const int Clientprocessexitwait = 10 * 1000; diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs index 4b711e25aa..209fc9c54e 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs @@ -446,8 +446,8 @@ public void DiscoveryTestsMarksAllSourcesAsNotDiscovered() // Assert CollectionAssert.AreEquivalent(inputSource, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered)); - Assert.AreEqual(0, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered).Count); - Assert.AreEqual(0, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.FullyDiscovered).Count); + Assert.IsEmpty(_discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered)); + Assert.IsEmpty(_discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.FullyDiscovered)); } [TestMethod] @@ -601,7 +601,7 @@ public void HandleDiscoveredTestsMarksDiscoveryStatus() }); // Assert - Assert.AreEqual(0, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered).Count); + Assert.IsEmpty(_discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered)); CollectionAssert.AreEquivalent( new List { "d" }, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered)); @@ -631,8 +631,8 @@ public void HandleDiscoveryCompleteWhenAbortedNoPastDiscoveryAndNoLastCunkNotifi CollectionAssert.AreEquivalent( new[] { "a", "b" }, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered)); - Assert.AreEqual(0, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered).Count); - Assert.AreEqual(0, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.FullyDiscovered).Count); + Assert.IsEmpty(_discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered)); + Assert.IsEmpty(_discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.FullyDiscovered)); } [TestMethod] @@ -664,7 +664,7 @@ public void HandleDiscoveryCompleteWhenAbortedPastDiscoveryAndNoLastCunkNotifies CollectionAssert.AreEquivalent( new[] { "b" }, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered)); - Assert.AreEqual(0, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered).Count); + Assert.IsEmpty(_discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered)); } [TestMethod] @@ -724,7 +724,7 @@ public void HandleDiscoveryCompleteWhenAbortedPastDiscoveryAndLastCunkNotifiesWi CollectionAssert.AreEquivalent( new[] { "d" }, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.PartiallyDiscovered)); - Assert.AreEqual(0, _discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered).Count); + Assert.IsEmpty(_discoveryDataAggregator.GetSourcesWithStatus(DiscoveryStatus.NotDiscovered)); } private void InvokeAndVerifyDiscoverTests(bool skipDefaultAdapters) diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerWithDataCollectionTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerWithDataCollectionTests.cs index 504053c7eb..8e5107b786 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerWithDataCollectionTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerWithDataCollectionTests.cs @@ -96,7 +96,7 @@ public void InitializeShouldSaveExceptionMessagesIfThrownByDataCollectionProcess proxyExecutionManager.Initialize(false); Assert.IsNotNull(proxyExecutionManager.DataCollectionRunEventsHandler.Messages); Assert.AreEqual(TestMessageLevel.Error, proxyExecutionManager.DataCollectionRunEventsHandler.Messages[0].Item1); - StringAssert.Contains(proxyExecutionManager.DataCollectionRunEventsHandler.Messages[0].Item2, "MyException"); + Assert.Contains("MyException", proxyExecutionManager.DataCollectionRunEventsHandler.Messages[0].Item2!); } [TestMethod] @@ -110,7 +110,7 @@ public void UpdateTestProcessStartInfoShouldUpdateDataCollectionPortArg() var proxyExecutionManager = new TestableProxyExecutionManagerWithDataCollection(_mockRequestSender.Object, _mockTestHostManager.Object, _mockDataCollectionManager.Object); proxyExecutionManager.UpdateTestProcessStartInfoWrapper(testProcessStartInfo); - Assert.IsTrue(testProcessStartInfo.Arguments.Contains("--datacollectionport 0")); + Assert.Contains("--datacollectionport 0", testProcessStartInfo.Arguments); } [TestMethod] @@ -130,7 +130,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgTrueIfTelem proxyExecutionManager.UpdateTestProcessStartInfoWrapper(testProcessStartInfo); // Verify. - Assert.IsTrue(testProcessStartInfo.Arguments.Contains("--telemetryoptedin true")); + Assert.Contains("--telemetryoptedin true", testProcessStartInfo.Arguments); } [TestMethod] @@ -150,7 +150,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgFalseIfTele proxyExecutionManager.UpdateTestProcessStartInfoWrapper(testProcessStartInfo); // Verify. - Assert.IsTrue(testProcessStartInfo.Arguments.Contains("--telemetryoptedin false")); + Assert.Contains("--telemetryoptedin false", testProcessStartInfo.Arguments); } [TestMethod] @@ -184,7 +184,7 @@ public void LaunchProcessWithDebuggerAttachedShouldUpdateEnvironmentVariables() proxyExecutionManager.LaunchProcessWithDebuggerAttached(testProcessStartInfo); // Verify. - Assert.IsTrue(launchedStartInfo != null, "Failed to get the start info"); + Assert.IsNotNull(launchedStartInfo, "Failed to get the start info"); foreach (var envVaribale in testProcessStartInfo.EnvironmentVariables) { Assert.AreEqual(envVaribale.Value, launchedStartInfo.EnvironmentVariables![envVaribale.Key], $"Expected environment variable {envVaribale.Key} : {envVaribale.Value} not found"); @@ -192,7 +192,7 @@ public void LaunchProcessWithDebuggerAttachedShouldUpdateEnvironmentVariables() mockRunEventsHandler.Verify(r => r.HandleRawMessage(raw1)); mockRunEventsHandler.Verify(r => r.HandleRawMessage(raw2)); - Assert.AreEqual(0, proxyExecutionManager.DataCollectionRunEventsHandler.RawMessages.Count); + Assert.IsEmpty(proxyExecutionManager.DataCollectionRunEventsHandler.RawMessages); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs index 2d8a788b28..e8d3719b35 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs @@ -123,8 +123,8 @@ public void SetupChannelOutcomeShouldTakeTesthostSessionSupportIntoAccount( TesthostFriendlyName = testhostFriendlyName }; - Assert.IsTrue(testOperationManager.IsTesthostCompatibleWithTestSessions() == expectedCompatibilityCheckResult); - Assert.IsTrue(testOperationManager.SetupChannel([], DefaultRunSettings) == expectedSetupResult); + Assert.AreEqual(expectedCompatibilityCheckResult, testOperationManager.IsTesthostCompatibleWithTestSessions()); + Assert.AreEqual(expectedSetupResult, testOperationManager.SetupChannel([], DefaultRunSettings)); } [TestMethod] @@ -302,7 +302,9 @@ public void SetupChannelShouldThrowTestPlatformExceptionIfRequestCancelledDuring SetupTestHostLaunched(true); _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny())).Returns(false); +#pragma warning disable MSTEST0049 // CancellationToken not applicable in Moq callback _mockTestHostManager.Setup(rs => rs.LaunchTestHostAsync(It.IsAny(), It.IsAny())).Callback(() => Task.Run(() => throw new OperationCanceledException())); +#pragma warning restore MSTEST0049 var cancellationTokenSource = new CancellationTokenSource(); var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object, cancellationTokenSource); @@ -474,7 +476,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgTrueIfTelem testOperationManager.SetupChannel([], DefaultRunSettings); // Verify. - Assert.IsTrue(receivedTestProcessInfo.Arguments!.Contains("--telemetryoptedin true")); + Assert.Contains("--telemetryoptedin true", receivedTestProcessInfo.Arguments!); } [TestMethod] @@ -497,7 +499,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgFalseIfTele testOperationManager.SetupChannel([], DefaultRunSettings); // Verify. - Assert.IsTrue(receivedTestProcessInfo.Arguments!.Contains("--telemetryoptedin false")); + Assert.Contains("--telemetryoptedin false", receivedTestProcessInfo.Arguments!); } [MemberNotNull(nameof(_mockProcessHelper), nameof(_mockFileHelper), nameof(_mockEnvironment), nameof(_mockRunsettingHelper), nameof(_mockWindowsRegistry), nameof(_mockEnvironmentVariableHelper))] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs index e78923a316..4e9ff82e57 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs @@ -445,7 +445,7 @@ public void DequeueProxyTwoConsecutiveTimesWithEnqueueShouldBeSuccessful() testSessionCriteria.RunSettings), mockProxyOperationManager.Object); - Assert.AreEqual(true, proxyManager.EnqueueProxy(mockProxyOperationManager.Object.Id)); + Assert.IsTrue(proxyManager.EnqueueProxy(mockProxyOperationManager.Object.Id)); // Call to DequeueProxy succeeds when called with the same runsettings as before. Assert.AreEqual(proxyManager.DequeueProxy( diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs index 465ce2effa..f481990759 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs @@ -123,7 +123,7 @@ public void HandleRawMessageShouldInvokeAfterTestRunEndAndReturnInvokedDataColle { var testRunCompleteArgs = o as TestRunCompletePayload; Assert.IsNotNull(testRunCompleteArgs); - Assert.AreEqual(1, testRunCompleteArgs.TestRunCompleteArgs!.InvokedDataCollectors.Count); + Assert.ContainsSingle(testRunCompleteArgs.TestRunCompleteArgs!.InvokedDataCollectors); Assert.AreEqual(invokedDataCollectors[0], testRunCompleteArgs.TestRunCompleteArgs.InvokedDataCollectors[0]); }); @@ -132,7 +132,7 @@ public void HandleRawMessageShouldInvokeAfterTestRunEndAndReturnInvokedDataColle var testRunCompleteEventArgs2 = new TestRunCompleteEventArgs(null, false, false, null, new Collection(), new Collection(), new TimeSpan()); _testRunEventHandler.HandleTestRunComplete(testRunCompleteEventArgs2, null, null, null); - Assert.AreEqual(1, testRunCompleteEventArgs2.InvokedDataCollectors.Count); + Assert.ContainsSingle(testRunCompleteEventArgs2.InvokedDataCollectors); Assert.AreEqual(invokedDataCollectors[0], testRunCompleteEventArgs2.InvokedDataCollectors[0]); _proxyDataCollectionManager.Verify( @@ -157,8 +157,8 @@ public void GetCombinedAttachmentSetsShouldReturnCombinedAttachments() var result = DataCollectionTestRunEventsHandler.GetCombinedAttachmentSets(attachments1, attachments2); - Assert.AreEqual(1, result.Count); - Assert.AreEqual(2, result.First().Attachments.Count); + Assert.ContainsSingle(result); + Assert.HasCount(2, result.First().Attachments); } [TestMethod] @@ -171,8 +171,8 @@ public void GetCombinedAttachmentSetsShouldReturnFirstArgumentIfSecondArgumentIs var result = DataCollectionTestRunEventsHandler.GetCombinedAttachmentSets(attachments1, null); - Assert.AreEqual(1, result.Count); - Assert.AreEqual(1, result.First().Attachments.Count); + Assert.ContainsSingle(result); + Assert.ContainsSingle(result.First().Attachments); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs index 87c3f5dfb6..3b8fbf57b0 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -65,11 +65,11 @@ public void CodeBasePathsAreDeduplicatedWithCaseIgnoring() var inProcDataCollectionExtensionManager = new TestableInProcDataCollectionExtensionManager(_settingsXml, _mockTestEventsPublisher.Object, null, testPluginCache, _mockFileHelper.Object); - Assert.AreEqual(3, inProcDataCollectionExtensionManager.CodeBasePaths.Count); // "CodeBasePaths" contains the two extensions(after removing duplicates) and the "_defaultCodebase" + Assert.HasCount(3, inProcDataCollectionExtensionManager.CodeBasePaths); // "CodeBasePaths" contains the two extensions(after removing duplicates) and the "_defaultCodebase" - Assert.IsTrue(inProcDataCollectionExtensionManager.CodeBasePaths.Contains(null)); - Assert.IsTrue(inProcDataCollectionExtensionManager.CodeBasePaths.Contains(directory1)); - Assert.IsTrue(inProcDataCollectionExtensionManager.CodeBasePaths.Contains(directory2)); + Assert.Contains((string?)null, inProcDataCollectionExtensionManager.CodeBasePaths); + Assert.Contains(directory1, inProcDataCollectionExtensionManager.CodeBasePaths); + Assert.Contains(directory2, inProcDataCollectionExtensionManager.CodeBasePaths); } @@ -79,7 +79,7 @@ public void InProcDataCollectionExtensionManagerShouldLoadsDataCollectorsFromRun var dataCollector = (MockDataCollector)_inProcDataCollectionManager.InProcDataCollectors.First().Value; Assert.IsTrue(_inProcDataCollectionManager.IsInProcDataCollectionEnabled, "InProcDataCollection must be enabled if runsettings contains inproc datacollectors."); - Assert.AreEqual(1, _inProcDataCollectionManager.InProcDataCollectors.Count, "One Datacollector must be registered"); + Assert.ContainsSingle(_inProcDataCollectionManager.InProcDataCollectors, "One Datacollector must be registered"); Equals(dataCollector.AssemblyQualifiedName, "TestImpactListener.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7ccb7239ffde675a"); Equals(dataCollector.CodeBase, Path.Combine(Temp, "repos", "MSTest", "src", "managed", "TestPlatform", "TestImpactListener.Tests", "bin", "Debug", "TestImpactListener.Tests.dll")); @@ -231,11 +231,11 @@ public void TriggerSessionStartShouldBeCalledWithCorrectTestSources() var mockDataCollector = (MockDataCollector)_inProcDataCollectionManager.InProcDataCollectors.Values.First(); _mockTestEventsPublisher.Raise(x => x.SessionStart += null, new SessionStartEventArgs(properties)); - Assert.IsTrue((mockDataCollector.TestSessionStartCalled == 1), "TestSessionStart must be called on datacollector"); + Assert.AreEqual(1, mockDataCollector.TestSessionStartCalled, "TestSessionStart must be called on datacollector"); Assert.IsNotNull(mockDataCollector.TestSources); - Assert.IsTrue(mockDataCollector.TestSources.Contains("testsource1.dll")); - Assert.IsTrue(mockDataCollector.TestSources.Contains("testsource2.dll")); + Assert.Contains("testsource1.dll", mockDataCollector.TestSources); + Assert.Contains("testsource2.dll", mockDataCollector.TestSources); } @@ -245,10 +245,10 @@ public void TriggerSessionStartShouldCallInProcDataCollector() _mockTestEventsPublisher.Raise(x => x.SessionStart += null, new SessionStartEventArgs()); var mockDataCollector = (MockDataCollector)_inProcDataCollectionManager.InProcDataCollectors.Values.First(); - Assert.IsTrue((mockDataCollector.TestSessionStartCalled == 1), "TestSessionStart must be called on datacollector"); - Assert.IsTrue((mockDataCollector.TestSessionEndCalled == 0), "TestSessionEnd must NOT be called on datacollector"); - Assert.IsTrue((mockDataCollector.TestCaseStartCalled == 0), "TestCaseStart must NOT be called on datacollector"); - Assert.IsTrue((mockDataCollector.TestCaseEndCalled == 0), "TestCaseEnd must NOT be called on datacollector"); + Assert.AreEqual(1, mockDataCollector.TestSessionStartCalled, "TestSessionStart must be called on datacollector"); + Assert.AreEqual(0, mockDataCollector.TestSessionEndCalled, "TestSessionEnd must NOT be called on datacollector"); + Assert.AreEqual(0, mockDataCollector.TestCaseStartCalled, "TestCaseStart must NOT be called on datacollector"); + Assert.AreEqual(0, mockDataCollector.TestCaseEndCalled, "TestCaseEnd must NOT be called on datacollector"); } [TestMethod] @@ -257,10 +257,10 @@ public void TriggerSessionEndShouldCallInProcDataCollector() _mockTestEventsPublisher.Raise(x => x.SessionEnd += null, new SessionEndEventArgs()); var mockDataCollector = (MockDataCollector)_inProcDataCollectionManager.InProcDataCollectors.Values.First(); - Assert.IsTrue((mockDataCollector.TestSessionStartCalled == 0), "TestSessionEnd must NOT be called on datacollector"); - Assert.IsTrue((mockDataCollector.TestSessionEndCalled == 1), "TestSessionStart must be called on datacollector"); - Assert.IsTrue((mockDataCollector.TestCaseStartCalled == 0), "TestCaseStart must NOT be called on datacollector"); - Assert.IsTrue((mockDataCollector.TestCaseEndCalled == 0), "TestCaseEnd must NOT be called on datacollector"); + Assert.AreEqual(0, mockDataCollector.TestSessionStartCalled, "TestSessionEnd must NOT be called on datacollector"); + Assert.AreEqual(1, mockDataCollector.TestSessionEndCalled, "TestSessionStart must be called on datacollector"); + Assert.AreEqual(0, mockDataCollector.TestCaseStartCalled, "TestCaseStart must NOT be called on datacollector"); + Assert.AreEqual(0, mockDataCollector.TestCaseEndCalled, "TestCaseEnd must NOT be called on datacollector"); } [TestMethod] @@ -273,8 +273,8 @@ public void TriggerTestCaseStartShouldCallInProcDataCollector() var mockDataCollector = (MockDataCollector)_inProcDataCollectionManager.InProcDataCollectors.Values.First(); - Assert.IsTrue((mockDataCollector.TestCaseStartCalled == 1), "TestCaseStart must be called on datacollector"); - Assert.IsTrue((mockDataCollector.TestCaseEndCalled == 0), "TestCaseEnd must NOT be called on datacollector"); + Assert.AreEqual(1, mockDataCollector.TestCaseStartCalled, "TestCaseStart must be called on datacollector"); + Assert.AreEqual(0, mockDataCollector.TestCaseEndCalled, "TestCaseEnd must NOT be called on datacollector"); } [TestMethod] @@ -289,8 +289,8 @@ public void TriggerTestCaseEndShouldtBeCalledMultipleTimesInDataDrivenScenario() _mockTestEventsPublisher.Raise(x => x.TestCaseEnd += null, new TestCaseEndEventArgs(testCase, TestOutcome.Failed)); var mockDataCollector = (MockDataCollector)_inProcDataCollectionManager.InProcDataCollectors.Values.First(); - Assert.IsTrue((mockDataCollector.TestCaseStartCalled == 2), "TestCaseStart must only be called once"); - Assert.IsTrue((mockDataCollector.TestCaseEndCalled == 2), "TestCaseEnd must only be called once"); + Assert.AreEqual(2, mockDataCollector.TestCaseStartCalled, "TestCaseStart must only be called once"); + Assert.AreEqual(2, mockDataCollector.TestCaseEndCalled, "TestCaseEnd must only be called once"); } internal class TestableInProcDataCollectionExtensionManager : InProcDataCollectionExtensionManager diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs index 1ea58a735f..51ce13b0a8 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs @@ -178,7 +178,7 @@ public void BeforeTestRunStartShouldReturnDataCollectorParameters() x => x.SendBeforeTestRunStartAndGetResult(It.IsAny(), sourceList, false, It.IsAny()), Times.Once); Assert.IsNotNull(result); Assert.AreEqual(res.DataCollectionEventsPort, result.DataCollectionEventsPort); - Assert.AreEqual(res.EnvironmentVariables.Count, result.EnvironmentVariables!.Count); + Assert.HasCount(res.EnvironmentVariables.Count, result.EnvironmentVariables!); } [TestMethod] @@ -192,7 +192,7 @@ public void BeforeTestRunStartsShouldInvokeRunEventsHandlerIfExceptionIsThrown() var result = _proxyDataCollectionManager.BeforeTestRunStart(true, true, mockRunEventsHandler.Object); mockRunEventsHandler.Verify(eh => eh.HandleLogMessage(TestMessageLevel.Error, It.IsRegex("Exception of type 'System.Exception' was thrown..*")), Times.Once); - Assert.AreEqual(0, result.EnvironmentVariables!.Count); + Assert.IsEmpty(result.EnvironmentVariables!); Assert.IsFalse(result.AreTestCaseLevelEventsRequired); Assert.AreEqual(0, result.DataCollectionEventsPort); } @@ -212,7 +212,7 @@ public void SendBeforeTestRunStartAndGetResultShouldBeInvokedWithCorrectTestSour x => x.SendBeforeTestRunStartAndGetResult(string.Empty, testSources, false, It.IsAny()), Times.Once); Assert.IsNotNull(result); Assert.AreEqual(res.DataCollectionEventsPort, result.DataCollectionEventsPort); - Assert.AreEqual(res.EnvironmentVariables.Count, result.EnvironmentVariables!.Count); + Assert.HasCount(res.EnvironmentVariables.Count, result.EnvironmentVariables!); } [TestMethod] @@ -238,8 +238,8 @@ public void AfterTestRunEndShouldReturnAttachments(bool telemetryOptedIn) var result = _proxyDataCollectionManager.AfterTestRunEnd(false, null); Assert.IsNotNull(result); - Assert.AreEqual(1, result.Attachments!.Count); - Assert.IsNotNull(result.Attachments[0]); + Assert.ContainsSingle(result.Attachments!); + Assert.IsNotNull(result.Attachments![0]); Assert.AreEqual(dispName, result.Attachments[0].DisplayName); Assert.AreEqual(uri, result.Attachments[0].Uri); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyOutOfProcDataCollectionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyOutOfProcDataCollectionManagerTests.cs index 23b888d436..456059f0c0 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyOutOfProcDataCollectionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyOutOfProcDataCollectionManagerTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -50,8 +50,8 @@ public void TriggerTestCaseEndShouldReturnCacheAttachmentsAndAssociateWithTestRe { _mockTestEventsPublisher.Raise(x => x.TestResult += null, new TestResultEventArgs(_testResult)); - Assert.AreEqual(1, _testResult.Attachments.Count); - Assert.IsTrue(_testResult.Attachments[0].Attachments[0].Uri.OriginalString.Contains("attachment.txt")); + Assert.ContainsSingle(_testResult.Attachments); + Assert.Contains("attachment.txt", _testResult.Attachments[0].Attachments[0].Uri.OriginalString); } [TestMethod] @@ -62,6 +62,6 @@ public void TriggerSendTestResultShouldDeleteTheAttachmentsFromCache() _testResult = new VisualStudio.TestPlatform.ObjectModel.TestResult(_testcase); _mockTestEventsPublisher.Raise(x => x.TestResult += null, new TestResultEventArgs(_testResult)); - Assert.AreEqual(0, _testResult.Attachments.Count); + Assert.IsEmpty(_testResult.Attachments); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs index 802f7de7bd..bd3a86946d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs @@ -528,7 +528,7 @@ public void LoadTestsShouldCallIntoTheAdapterWithTheRightTestCaseSink() InvokeLoadTestWithMockSetup(); Assert.IsTrue(ManagedDllTestDiscoverer.IsManagedDiscoverTestCalled); - Assert.AreEqual(2, _discoveryResultCache.Tests.Count); + Assert.HasCount(2, _discoveryResultCache.Tests); } [TestMethod] @@ -536,7 +536,7 @@ public void LoadTestsShouldNotShowAnyWarningOnTestsDiscovered() { InvokeLoadTestWithMockSetup(); - Assert.AreEqual(2, _discoveryResultCache.Tests.Count); + Assert.HasCount(2, _discoveryResultCache.Tests); _messageLoggerMock.Verify(m => m.SendMessage(TestMessageLevel.Warning, It.IsAny()), Times.Never); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs index ab9d44ffed..d3a70f8728 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs @@ -311,7 +311,7 @@ public void DiscoveryTestsShouldSendAbortValuesCorrectlyIfAbortionHappened() _discoveryManager.Abort(mockHandler.Object); // Assert - Assert.AreEqual(true, receivedDiscoveryCompleteEventArgs!.IsAborted); + Assert.IsTrue(receivedDiscoveryCompleteEventArgs!.IsAborted); Assert.AreEqual(-1, receivedDiscoveryCompleteEventArgs.TotalCount); } #endregion diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryResultCacheTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryResultCacheTests.cs index c8e2a92c6d..b375d55147 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryResultCacheTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryResultCacheTests.cs @@ -15,13 +15,15 @@ namespace TestPlatform.CrossPlatEngine.UnitTests.Discovery; [TestClass] public class DiscoveryResultCacheTests { + public TestContext TestContext { get; set; } + [TestMethod] public void DiscoveryResultCacheConstructorShouldInitializeDiscoveredTestsList() { var cache = new DiscoveryResultCache(1000, TimeSpan.FromHours(1), (tests) => { }); Assert.IsNotNull(cache.Tests); - Assert.AreEqual(0, cache.Tests.Count); + Assert.IsEmpty(cache.Tests); } [TestMethod] @@ -40,7 +42,7 @@ public void AddTestShouldAddATestCaseToTheList() var testCase = new TestCase("A.C.M", new Uri("executor://unittest"), "A"); cache.AddTest(testCase); - Assert.AreEqual(1, cache.Tests.Count); + Assert.ContainsSingle(cache.Tests); Assert.AreEqual(testCase, cache.Tests[0]); } @@ -67,7 +69,7 @@ public void AddTestShouldReportTestCasesIfMaxCacheSizeIsMet() cache.AddTest(testCase2); Assert.IsNotNull(reportedTestCases); - Assert.AreEqual(2, reportedTestCases.Count); + Assert.HasCount(2, reportedTestCases); CollectionAssert.AreEqual(new List { testCase1, testCase2 }, reportedTestCases.ToList()); } @@ -82,7 +84,7 @@ public void AddTestShouldResetTestListOnceCacheSizeIsMet() cache.AddTest(testCase2); Assert.IsNotNull(cache.Tests); - Assert.AreEqual(0, cache.Tests.Count); + Assert.IsEmpty(cache.Tests); // Validate that total tests is no reset though. Assert.AreEqual(2, cache.TotalDiscoveredTests); @@ -95,11 +97,11 @@ public void AddTestShouldReportTestCasesIfCacheTimeoutIsMet() var cache = new DiscoveryResultCache(100, TimeSpan.FromMilliseconds(10), (tests) => reportedTestCases = tests); var testCase = new TestCase("A.C.M", new Uri("executor://unittest"), "A"); - Task.Delay(20).Wait(); + Task.Delay(20, TestContext.CancellationToken).Wait(TestContext.CancellationToken); cache.AddTest(testCase); Assert.IsNotNull(reportedTestCases); - Assert.AreEqual(1, reportedTestCases.Count); + Assert.ContainsSingle(reportedTestCases); Assert.AreEqual(testCase, reportedTestCases.ToArray()[0]); } @@ -110,11 +112,11 @@ public void AddTestShouldResetTestListIfCacheTimeoutIsMet() var cache = new DiscoveryResultCache(100, TimeSpan.FromMilliseconds(10), (tests) => reportedTestCases = tests); var testCase = new TestCase("A.C.M", new Uri("executor://unittest"), "A"); - Task.Delay(20).Wait(); + Task.Delay(20, TestContext.CancellationToken).Wait(TestContext.CancellationToken); cache.AddTest(testCase); Assert.IsNotNull(cache.Tests); - Assert.AreEqual(0, cache.Tests.Count); + Assert.IsEmpty(cache.Tests); // Validate that total tests is no reset though. Assert.AreEqual(1, cache.TotalDiscoveredTests); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/TestCaseDiscoverySinkTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/TestCaseDiscoverySinkTests.cs index aca9334005..805af71c75 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/TestCaseDiscoverySinkTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/TestCaseDiscoverySinkTests.cs @@ -35,7 +35,7 @@ public void SendTestCaseShouldSendTestCasesToCache() // Assert that the cache has the test case. Assert.IsNotNull(cache.Tests); - Assert.AreEqual(1, cache.Tests.Count); + Assert.ContainsSingle(cache.Tests); Assert.AreEqual(testCase, cache.Tests[0]); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs index 83219994f4..f5978779e3 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs @@ -38,6 +38,8 @@ public class TestRequestHandlerTests private readonly TestHostConnectionInfo _testHostConnectionInfo; private readonly JobQueue _jobQueue; + public TestContext TestContext { get; set; } + public TestRequestHandlerTests() { _mockCommunicationClient = new Mock(); @@ -132,7 +134,7 @@ public void ProcessRequestsShouldProcessMessagesUntilSessionCompleted() var task = ProcessRequestsAsync(_mockTestHostManagerFactory.Object); SendSessionEnd(); - Assert.IsTrue(task.Wait(2000)); + Assert.IsTrue(task.Wait(2000, TestContext.CancellationToken)); } #region Version Check Protocol @@ -489,6 +491,7 @@ private void SendSessionEnd() SendMessageOnChannel(new Message { MessageType = MessageType.SessionEnd, Payload = string.Empty }); } +#pragma warning disable MSTEST0049 // Use 'TestContext.CancellationToken' - helper methods not in test context private Task ProcessRequestsAsync() { return Task.Run(() => _requestHandler.ProcessRequests(new Mock().Object)); @@ -498,6 +501,7 @@ private Task ProcessRequestsAsync(ITestHostManagerFactory testHostManagerFactory { return Task.Run(() => _requestHandler.ProcessRequests(testHostManagerFactory)); } +#pragma warning restore MSTEST0049 private string Serialize(Message message) { diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs index a52df4af69..b72c2abb67 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs @@ -372,7 +372,7 @@ public void RunTestsShouldNotAddExecutorUriToExecutorUriListIfNoTestsAreRun() _runTestsInstance.RunTests(); - Assert.AreEqual(0, _runTestsInstance.GetExecutorUrisThatRanTests.Count); + Assert.IsEmpty(_runTestsInstance.GetExecutorUrisThatRanTests); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs index 971fff89a2..8fa8bb9a94 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs @@ -88,7 +88,7 @@ public void InitializeShouldLoadAndInitializeAllExtensions() Assert.IsNotNull(TestPluginCache.Instance.TestExtensions); // Executors - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestExecutors!.Count > 0); + Assert.IsNotEmpty(TestPluginCache.Instance.TestExtensions.TestExecutors!); var allExecutors = TestExecutorExtensionManager.Create().TestExtensions; foreach (var executor in allExecutors) @@ -97,7 +97,7 @@ public void InitializeShouldLoadAndInitializeAllExtensions() } // Settings Providers - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestSettingsProviders!.Count > 0); + Assert.IsNotEmpty(TestPluginCache.Instance.TestExtensions.TestSettingsProviders!); var settingsProviders = SettingsProviderExtensionManager.Create().SettingsProvidersMap.Values; foreach (var provider in settingsProviders) diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/TestRunCacheTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/TestRunCacheTests.cs index 4292a53b3d..3beac92af0 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/TestRunCacheTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/TestRunCacheTests.cs @@ -77,8 +77,8 @@ public void OnTestStartedShouldReportResultsOnCacheHit() Assert.AreEqual(1, tester.CacheHitCount); Assert.AreEqual(0, cache.TotalExecutedTests); - Assert.AreEqual(0, cache.TestResults.Count); - Assert.AreEqual(0, cache.InProgressTests.Count); + Assert.IsEmpty(cache.TestResults); + Assert.IsEmpty(cache.InProgressTests); Assert.AreEqual(2, tester.TotalInProgressTestsReceived); } @@ -149,7 +149,7 @@ public void OnNewTestResultShouldRemoveTestCaseFromInProgressList() cache.OnNewTestResult(tr); } - Assert.AreEqual(0, cache.InProgressTests.Count); + Assert.IsEmpty(cache.InProgressTests); } [TestMethod] @@ -167,7 +167,7 @@ public void OnNewTestResultShouldReportTestResultsWhenMaxCacheSizeIsHit() Assert.AreEqual(1, tester.CacheHitCount); Assert.AreEqual(cacheSize, cache.TotalExecutedTests); - Assert.AreEqual(0, cache.TestResults.Count); + Assert.IsEmpty(cache.TestResults); } [TestMethod] @@ -186,7 +186,7 @@ public void OnNewTestResultShouldNotFireIfMaxCacheSizeIsNotHit() Assert.AreEqual(0, tester.CacheHitCount); Assert.AreEqual(executedTests, cache.TotalExecutedTests); - Assert.AreEqual(executedTests, cache.TestResults.Count); + Assert.HasCount((int)executedTests, cache.TestResults); } [TestMethod] @@ -206,7 +206,7 @@ public void OnNewTestResultShouldReportResultsMultipleTimes() Assert.AreEqual(4, tester.CacheHitCount); Assert.AreEqual(executedTests, cache.TotalExecutedTests); - Assert.AreEqual(5, cache.TestResults.Count); + Assert.HasCount(5, cache.TestResults); } #endregion @@ -248,7 +248,7 @@ public void OnTestCompletionShouldUpdateInProgressList() cache.OnTestStarted(tr.TestCase); Assert.IsTrue(cache.OnTestCompletion(tr.TestCase)); - Assert.AreEqual(0, cache.InProgressTests.Count); + Assert.IsEmpty(cache.InProgressTests); } } @@ -272,7 +272,7 @@ public void OnTestCompletionShouldUpdateInProgressListWhenTestHasSameId() Assert.IsTrue(cache.OnTestCompletion(clone)); - Assert.AreEqual(0, cache.InProgressTests.Count); + Assert.IsEmpty(cache.InProgressTests); } } @@ -290,7 +290,7 @@ public void OnTestCompleteShouldNotRemoveTestCaseFromInProgressListForUnrelatedT var tr2 = GetTestResult(1); Assert.IsFalse(cache.OnTestCompletion(tr2.TestCase)); - Assert.AreEqual(1, cache.InProgressTests.Count); + Assert.ContainsSingle(cache.InProgressTests); } #endregion @@ -332,7 +332,7 @@ public void GetLastChunkShouldResetTestResultsInCache() } cache.GetLastChunk(); - Assert.AreEqual(0, cache.TestResults.Count); + Assert.IsEmpty(cache.TestResults); } #endregion diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs index 420f2ab44c..ecf3e6f3f3 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs @@ -1075,7 +1075,7 @@ public void CreatedNonParallelExecutionManagerShouldBeInitialzedWithCorrectTestS var nonParallelExecutionManager = _testEngine.CreateNonParallelExecutionManager(_mockRequestData.Object, testRunCriteria, true, runtimeProviderInfo); Assert.IsInstanceOfType(nonParallelExecutionManager, typeof(ProxyExecutionManagerWithDataCollection)); - Assert.IsTrue(((ProxyExecutionManagerWithDataCollection)nonParallelExecutionManager).ProxyDataCollectionManager.Sources.Contains("1.dll")); - Assert.IsTrue(((ProxyExecutionManagerWithDataCollection)nonParallelExecutionManager).ProxyDataCollectionManager.Sources.Contains("2.dll")); + Assert.Contains("1.dll", ((ProxyExecutionManagerWithDataCollection)nonParallelExecutionManager).ProxyDataCollectionManager.Sources); + Assert.Contains("2.dll", ((ProxyExecutionManagerWithDataCollection)nonParallelExecutionManager).ProxyDataCollectionManager.Sources); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestExtensionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestExtensionManagerTests.cs index c4c8293cd2..dda80177ac 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestExtensionManagerTests.cs @@ -47,6 +47,6 @@ public void ClearExtensionsShouldClearExtensionsInCache() _testExtensionManager.ClearExtensions(); - Assert.AreEqual(0, TestPluginCache.Instance.GetExtensionPaths(string.Empty).Count); + Assert.IsEmpty(TestPluginCache.Instance.GetExtensionPaths(string.Empty)); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs index e0de60b0e8..128616b323 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs @@ -1033,9 +1033,9 @@ public void InitializeShouldPassConfigurationElementAsParameters() testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(4, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters["Key1"]); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(4, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters!["Key1"]); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); @@ -1073,9 +1073,9 @@ public void InitializeShouldSkipEmptyConfigurationValueInParameters() testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(3, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.IsFalse(ValidLoggerWithParameters.Parameters.TryGetValue("Key1", out var key1Value)); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(3, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.IsFalse(ValidLoggerWithParameters.Parameters!.TryGetValue("Key1", out var key1Value)); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); @@ -1114,9 +1114,9 @@ public void InitializeShouldUseLastValueInParametersForDuplicateConfigurationVal testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(4, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.AreEqual("Value3", ValidLoggerWithParameters.Parameters["Key1"]); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(4, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.AreEqual("Value3", ValidLoggerWithParameters.Parameters!["Key1"]); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); @@ -1185,9 +1185,9 @@ public void InitializeShouldInitializeFromAssemblyNameIfAllAttributesPresent() testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(4, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters["Key1"]); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(4, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters!["Key1"]); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); } @@ -1223,9 +1223,9 @@ public void InitializeShouldInitializeFromUriIfUriAndNamePresent() testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(4, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters["Key1"]); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(4, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters!["Key1"]); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); } @@ -1261,9 +1261,9 @@ public void InitializeShouldInitializeFromUriIfUnableToFromAssemblyName() testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(4, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters["Key1"]); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(4, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters!["Key1"]); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); } @@ -1299,9 +1299,9 @@ public void InitializeShouldInitializeFromNameIfUnableToFromUri() testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(4, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters["Key1"]); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(4, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters!["Key1"]); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); } @@ -1343,10 +1343,10 @@ public void InitializeShouldInitializeLoggersWithTestRunDirectoryIfPresentInRunS testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(4, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters["Key1"]); - Assert.AreEqual("DummyTestResultsFolder", ValidLoggerWithParameters.Parameters["testRunDirectory"]); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(4, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters!["Key1"]); + Assert.AreEqual("DummyTestResultsFolder", ValidLoggerWithParameters.Parameters!["testRunDirectory"]); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); } @@ -1387,10 +1387,10 @@ public void InitializeShouldInitializeLoggersWithDefaultTestRunDirectoryIfNotPre testLoggerManager.Initialize(settingsXml); Assert.AreEqual(1, ValidLoggerWithParameters.Counter); - Assert.AreEqual(4, ValidLoggerWithParameters.Parameters!.Count); // Two additional because of testRunDirectory and targetFramework - Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters["Key1"]); - Assert.AreEqual(Constants.DefaultResultsDirectory, ValidLoggerWithParameters.Parameters["testRunDirectory"]); - Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters["Key2"]); + Assert.HasCount(4, ValidLoggerWithParameters.Parameters!); // Two additional because of testRunDirectory and targetFramework + Assert.AreEqual("Value1", ValidLoggerWithParameters.Parameters!["Key1"]); + Assert.AreEqual(Constants.DefaultResultsDirectory, ValidLoggerWithParameters.Parameters!["testRunDirectory"]); + Assert.AreEqual("Value2", ValidLoggerWithParameters.Parameters!["Key2"]); mockMetricsCollection.Verify( rd => rd.Add(TelemetryDataConstants.LoggerUsed, "TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLogger2,TestPlatform.CrossPlatEngine.UnitTests.TestLoggerManagerTests+ValidLoggerWithParameters")); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Utilities/TestSourcesUtilityTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Utilities/TestSourcesUtilityTests.cs index ad0932b0f8..7af513de24 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Utilities/TestSourcesUtilityTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Utilities/TestSourcesUtilityTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; @@ -29,9 +29,9 @@ public void GetSourcesShouldAggregateSourcesIfMultiplePresentInAdapterSourceMap( var sources = TestSourcesUtility.GetSources(adapterSourceMap)!; Assert.AreEqual(5, sources.Count()); - Assert.IsTrue(sources.Contains("source1.dll")); - Assert.IsTrue(sources.Contains("source2.dll")); - Assert.IsTrue(sources.Contains("source3.dll")); + Assert.Contains("source1.dll", sources); + Assert.Contains("source2.dll", sources); + Assert.Contains("source3.dll", sources); } [TestMethod] @@ -44,8 +44,8 @@ public void GetSourcesShouldGetDistinctSourcesFromTestCases() var sources = TestSourcesUtility.GetSources(tests); Assert.AreEqual(2, sources.Count()); - Assert.IsTrue(sources.Contains("source1.dll")); - Assert.IsTrue(sources.Contains("source2.dll")); + Assert.Contains("source1.dll", sources); + Assert.Contains("source2.dll", sources); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs index e8235bb6fd..b48dd14294 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs @@ -41,6 +41,8 @@ public class BlameCollectorTests private readonly XmlElement? _configurationElement; private readonly string _filepath; + public TestContext TestContext { get; set; } = null!; + /// /// Initializes a new instance of the class. /// @@ -186,7 +188,7 @@ public void InitializeWithDumpForHangShouldCaptureADumpOnTimeout() _mockLogger.Object, _context); - hangBasedDumpcollected.Wait(1000); + hangBasedDumpcollected.Wait(1000, TestContext.CancellationToken); _mockProcessDumpUtility.Verify(x => x.StartHangBasedProcessDump(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>()), Times.Once); _mockProcessDumpUtility.Verify(x => x.GetDumpFiles(true, It.IsAny()), Times.Once); _mockDataCollectionSink.Verify(x => x.SendFileAsync(It.Is(y => y.Path == dumpFile)), Times.Once); @@ -220,7 +222,7 @@ public void InitializeWithDumpForHangShouldCaptureKillTestHostOnTimeoutEvenIfGet _mockLogger.Object, _context); - hangBasedDumpcollected.Wait(1000); + hangBasedDumpcollected.Wait(1000, TestContext.CancellationToken); _mockProcessDumpUtility.Verify(x => x.StartHangBasedProcessDump(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>()), Times.Once); _mockProcessDumpUtility.Verify(x => x.GetDumpFiles(true, It.IsAny()), Times.Once); } @@ -255,7 +257,7 @@ public void InitializeWithDumpForHangShouldCaptureKillTestHostOnTimeoutEvenIfAtt _mockLogger.Object, _context); - hangBasedDumpcollected.Wait(1000); + hangBasedDumpcollected.Wait(1000, TestContext.CancellationToken); _mockProcessDumpUtility.Verify(x => x.StartHangBasedProcessDump(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>()), Times.Once); _mockProcessDumpUtility.Verify(x => x.GetDumpFiles(true, It.IsAny()), Times.Once); _mockDataCollectionSink.Verify(x => x.SendFileAsync(It.Is(y => y.Path == dumpFile)), Times.Once); @@ -764,7 +766,7 @@ public void ConcurrentTestCaseStartAndEndEventsShouldNotCorruptState() { var task = Task.Run(() => { - barrier.SignalAndWait(); + barrier.SignalAndWait(TestContext.CancellationToken); for (int i = 0; i < 50; i++) { var testcase = new TestCase($"TestProject.UnitTest.TestMethod{Guid.NewGuid()}", new Uri("test:/abc"), "abc.dll"); @@ -776,12 +778,12 @@ public void ConcurrentTestCaseStartAndEndEventsShouldNotCorruptState() _mockDataColectionEvents.Raise(x => x.TestCaseStart += null, new TestCaseStartEventArgs(testcase)); _mockDataColectionEvents.Raise(x => x.TestCaseEnd += null, new TestCaseEndEventArgs(testcase, TestOutcome.Passed)); } - }); + }, TestContext.CancellationToken); tasks.Add(task); } // This must not throw due to concurrent collection modifications - Task.WaitAll(tasks.ToArray()); + Task.WaitAll(tasks.ToArray(), TestContext.CancellationToken); // Raise session end - all tests completed so no sequence file should be written _mockDataColectionEvents.Raise(x => x.SessionEnd += null, new SessionEndEventArgs(_dataCollectionContext)); diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/InactivityTimerTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/InactivityTimerTests.cs index 2014f39a7d..5b863ec00a 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/InactivityTimerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/InactivityTimerTests.cs @@ -14,12 +14,14 @@ public class InactivityTimerTests private int _callBackCount; private readonly ManualResetEventSlim _timerEvent = new(); + public TestContext TestContext { get; set; } = null!; + [TestMethod] public void InactivityTimerShouldResetAndCallbackWhenResetIsCalled() { var timer = new InactivityTimer(TimerCallback); timer.ResetTimer(TimeSpan.FromMilliseconds(1)); - _timerEvent.Wait(1000); + _timerEvent.Wait(1000, TestContext.CancellationToken); Assert.AreEqual(1, _callBackCount, "Should have fired once."); } diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/XmlReaderWriterTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/XmlReaderWriterTests.cs index c0a4676370..728c15c3d3 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/XmlReaderWriterTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/XmlReaderWriterTests.cs @@ -111,7 +111,7 @@ public void WriteTestSequenceShouldWriteFileStream() // Assert it has some data var data = Encoding.UTF8.GetString(stream.ToArray()); - Assert.IsTrue(data.Length > 0, "Stream should have some data."); + Assert.IsGreaterThan(0, data.Length, "Stream should have some data."); } /// diff --git a/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs index 726be3cd86..8d6b1c75e9 100644 --- a/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs @@ -75,13 +75,10 @@ public void InitializeShouldInitializeAllProperties() [TestMethod] public void InitializeShouldThrowExceptionIfTestRunDirectoryIsEmptyOrNull() { + _events = new Mock(); + _parameters[DefaultLoggerParameterNames.TestRunDirectory] = null!; Assert.ThrowsExactly( - () => - { - _events = new Mock(); - _parameters[DefaultLoggerParameterNames.TestRunDirectory] = null!; - _htmlLogger.Initialize(_events.Object, _parameters); - }); + () => _htmlLogger.Initialize(_events.Object, _parameters)); } [TestMethod] @@ -138,7 +135,7 @@ public void TestMessageHandlerShouldAddMessageInListIfItIsWarningAndError() _htmlLogger.TestMessageHandler(new object(), testRunMessageEventArgs2); var runLevelMessageErrorAndWarning = _htmlLogger.TestRunDetails!.RunLevelMessageErrorAndWarning!; - Assert.AreEqual(2, runLevelMessageErrorAndWarning.Count); + Assert.HasCount(2, runLevelMessageErrorAndWarning); Assert.AreEqual(message, runLevelMessageErrorAndWarning.First()); } @@ -299,7 +296,7 @@ public void TestResultHandlerShouldCreateOneTestEntryForEachTestCase() _htmlLogger.TestResultHandler(new object(), resultEventArg1.Object); _htmlLogger.TestResultHandler(new object(), resultEventArg2.Object); - Assert.AreEqual(2, _htmlLogger.TestRunDetails!.ResultCollectionList!.First().ResultList!.Count, "TestResultHandler is not creating test result entry for each test case"); + Assert.HasCount(2, _htmlLogger.TestRunDetails!.ResultCollectionList!.First().ResultList!, "TestResultHandler is not creating test result entry for each test case"); } [TestMethod] @@ -317,9 +314,9 @@ public void TestResultHandlerShouldCreateOneTestResultCollectionForOneSource() _htmlLogger.TestResultHandler(new object(), new Mock(result1).Object); _htmlLogger.TestResultHandler(new object(), new Mock(result2).Object); - Assert.AreEqual(2, _htmlLogger.TestRunDetails!.ResultCollectionList!.Count); - Assert.AreEqual("abc.dll", _htmlLogger.TestRunDetails.ResultCollectionList.First().Source); - Assert.AreEqual("def.dll", _htmlLogger.TestRunDetails.ResultCollectionList.Last().Source); + Assert.HasCount(2, _htmlLogger.TestRunDetails!.ResultCollectionList!); + Assert.AreEqual("abc.dll", _htmlLogger.TestRunDetails!.ResultCollectionList!.First().Source); + Assert.AreEqual("def.dll", _htmlLogger.TestRunDetails!.ResultCollectionList!.Last().Source); } [TestMethod] @@ -330,7 +327,7 @@ public void TestResultHandlerShouldAddFailedResultToFailedResultListInTestResult _htmlLogger.TestResultHandler(new object(), new Mock(result1).Object); - Assert.AreEqual(1, _htmlLogger.TestRunDetails!.ResultCollectionList!.First().FailedResultList!.Count); + Assert.HasCount(1, _htmlLogger.TestRunDetails!.ResultCollectionList!.First().FailedResultList!); } [TestMethod] @@ -348,7 +345,7 @@ public void TestResultHandlerShouldAddHierarchicalResultsForOrderedTest() _htmlLogger.TestResultHandler(new object(), new Mock(result1).Object); - Assert.AreEqual(1, _htmlLogger.TestRunDetails!.ResultCollectionList!.First().ResultList!.Count, "test handler is adding parent result correctly"); + Assert.HasCount(1, _htmlLogger.TestRunDetails!.ResultCollectionList!.First().ResultList!, "test handler is adding parent result correctly"); Assert.IsNull(_htmlLogger.TestRunDetails!.ResultCollectionList!.First().ResultList!.First().InnerTestResults, "test handler is adding child result correctly"); var result2 = new ObjectModel.TestResult(testCase2); @@ -362,8 +359,8 @@ public void TestResultHandlerShouldAddHierarchicalResultsForOrderedTest() _htmlLogger.TestResultHandler(new object(), new Mock(result2).Object); _htmlLogger.TestResultHandler(new object(), new Mock(result3).Object); - Assert.AreEqual(1, _htmlLogger.TestRunDetails!.ResultCollectionList!.First().ResultList!.Count, "test handler is adding parent result correctly"); - Assert.AreEqual(2, _htmlLogger.TestRunDetails.ResultCollectionList!.First().ResultList!.First().InnerTestResults!.Count, "test handler is adding child result correctly"); + Assert.HasCount(1, _htmlLogger.TestRunDetails!.ResultCollectionList!.First().ResultList!, "test handler is adding parent result correctly"); + Assert.HasCount(2, _htmlLogger.TestRunDetails.ResultCollectionList!.First().ResultList!.First().InnerTestResults!, "test handler is adding child result correctly"); } [TestMethod] @@ -413,7 +410,7 @@ public void TestCompleteHandlerShouldCreateCustomHtmlFileNamewithLogFileNameKey( _htmlLogger.Initialize(new Mock().Object, parameters); _htmlLogger.TestRunCompleteHandler(new object(), new TestRunCompleteEventArgs(null, false, true, null, null, null, TimeSpan.Zero)); - Assert.IsTrue(_htmlLogger.HtmlFilePath!.Contains("TestResult")); + Assert.Contains("TestResult", _htmlLogger.HtmlFilePath!); } [TestMethod] @@ -433,7 +430,7 @@ public void TestCompleteHandlerShouldCreateCustomHtmlFileNameWithLogPrefix() _htmlLogger.Initialize(new Mock().Object, parameters); _htmlLogger.TestRunCompleteHandler(new object(), new TestRunCompleteEventArgs(null, false, true, null, null, null, TimeSpan.Zero)); - Assert.IsFalse(_htmlLogger.HtmlFilePath!.Contains("__")); + Assert.DoesNotContain("__", _htmlLogger.HtmlFilePath!); } [TestMethod] @@ -453,7 +450,7 @@ public void TestCompleteHandlerShouldCreateCustomHtmlFileNameWithLogPrefixIfTarg _htmlLogger.Initialize(new Mock().Object, parameters); _htmlLogger.TestRunCompleteHandler(new object(), new TestRunCompleteEventArgs(null, false, true, null, null, null, TimeSpan.Zero)); - Assert.IsTrue(_htmlLogger.HtmlFilePath!.Contains("sample_net451")); + Assert.Contains("sample_net451", _htmlLogger.HtmlFilePath!); } [TestMethod] @@ -574,8 +571,8 @@ public void TestCompleteHandlerShouldWriteToXmlSerializerCorrectly() _htmlLogger.TestRunCompleteHandler(new object(), new TestRunCompleteEventArgs(null, false, true, null, null, null, TimeSpan.Zero)); _mockXmlSerializer.Verify(x => x.WriteObject(It.IsAny(), It.IsAny()), Times.Once); - Assert.IsTrue(_htmlLogger.XmlFilePath!.Contains(".xml")); - Assert.IsTrue(_htmlLogger.HtmlFilePath!.Contains(".html")); + Assert.Contains(".xml", _htmlLogger.XmlFilePath!); + Assert.Contains(".html", _htmlLogger.HtmlFilePath!); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs index 6d543b1212..4a1bf95e4f 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs @@ -42,6 +42,8 @@ public class TrxLoggerTests private TestableTrxLogger _testableTrxLogger; + public TestContext TestContext { get; set; } + public TrxLoggerTests() { _events = new Mock(); @@ -81,13 +83,10 @@ public void InitializeShouldNotThrowExceptionIfEventsIsNotNull() [TestMethod] public void InitializeShouldThrowExceptionIfTestRunDirectoryIsEmptyOrNull() { + var events = new Mock(); + _parameters[DefaultLoggerParameterNames.TestRunDirectory] = null!; Assert.ThrowsExactly( - () => - { - var events = new Mock(); - _parameters[DefaultLoggerParameterNames.TestRunDirectory] = null!; - _testableTrxLogger.Initialize(events.Object, _parameters); - }); + () => _testableTrxLogger.Initialize(events.Object, _parameters)); } [TestMethod] @@ -133,7 +132,7 @@ public void TestMessageHandlerShouldAddMessageInListIfItIsWarning() _testableTrxLogger.TestMessageHandler(new object(), trme); _testableTrxLogger.TestMessageHandler(new object(), trme); - Assert.AreEqual(2, _testableTrxLogger.GetRunLevelErrorsAndWarnings().Count); + Assert.HasCount(2, _testableTrxLogger.GetRunLevelErrorsAndWarnings()); } [TestMethod] @@ -143,7 +142,7 @@ public void TestMessageHandlerShouldAddMessageInListIfItIsError() TestRunMessageEventArgs trme = new(TestMessageLevel.Error, message); _testableTrxLogger.TestMessageHandler(new object(), trme); - Assert.AreEqual(1, _testableTrxLogger.GetRunLevelErrorsAndWarnings().Count); + Assert.HasCount(1, _testableTrxLogger.GetRunLevelErrorsAndWarnings()); } [TestMethod] @@ -658,7 +657,7 @@ public void DefaultTrxFileShouldIterateIfLogFileNameParameterNotPassed() var files = TestMultipleTrxLoggers(); - Assert.AreEqual(MultipleLoggerInstanceCount, files.Length, "All logger instances should get different file names!"); + Assert.HasCount(MultipleLoggerInstanceCount, files, "All logger instances should get different file names!"); } [TestMethod] @@ -666,7 +665,7 @@ public void TrxFileNameShouldNotIterate() { var files = TestMultipleTrxLoggers(); - Assert.AreEqual(1, files.Length, "All logger instances should get the same file name!"); + Assert.HasCount(1, files, "All logger instances should get the same file name!"); } [TestMethod] @@ -677,7 +676,7 @@ public void TrxPrefixFileNameShouldIterate() var files = TestMultipleTrxLoggers(); - Assert.AreEqual(MultipleLoggerInstanceCount, files.Length, "All logger instances should get different file names!"); + Assert.HasCount(MultipleLoggerInstanceCount, files, "All logger instances should get different file names!"); } private string?[] TestMultipleTrxLoggers() @@ -898,7 +897,7 @@ private static void ValidateResultAttributesInTrx(string trxFileName, Guid testI private static void ValidateTimeWithinUtcLimits(DateTimeOffset dateTime) { - Assert.IsTrue(dateTime.UtcDateTime.Subtract(DateTime.UtcNow) < new TimeSpan(0, 0, 0, 60)); + Assert.IsLessThan(new TimeSpan(0, 0, 0, 60), dateTime.UtcDateTime.Subtract(DateTime.UtcNow)); } private static string? GetElementValueFromTrx(string trxFileName, string fieldName) @@ -925,7 +924,7 @@ public void TestResultHandlerCountersShouldBeThreadSafe() var tasks = Enumerable.Range(0, threadCount).Select(t => Task.Run(() => { - barrier.SignalAndWait(); + barrier.SignalAndWait(TestContext.CancellationToken); for (int i = 0; i < testsPerThread; i++) { var testCase = CreateTestCase($"Test_{t}_{i}"); @@ -935,9 +934,9 @@ public void TestResultHandlerCountersShouldBeThreadSafe() }; _testableTrxLogger.TestResultHandler(new object(), new Mock(result).Object); } - })).ToArray(); + }, TestContext.CancellationToken)).ToArray(); - Task.WaitAll(tasks); + Task.WaitAll(tasks, TestContext.CancellationToken); Assert.AreEqual(threadCount * testsPerThread, _testableTrxLogger.TotalTestCount, "Total test count should be exact under concurrent updates"); diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs index a459932bfc..f6e826a411 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs @@ -75,7 +75,7 @@ public void ToCollectionEntriesShouldRenameAttachmentUriIfTheAttachmentNameIsSam _converter = new Converter(new FileHelper(), _trxFileHelper); List collectorDataEntries = _converter.ToCollectionEntries(attachmentSets, testRun, testResultsDirectory); - Assert.AreEqual(2, collectorDataEntries[0].Attachments.Count); + Assert.HasCount(2, collectorDataEntries[0].Attachments); Assert.AreEqual($@"{Environment.MachineName}{Path.DirectorySeparatorChar}123.coverage", ((ObjectModel.UriDataAttachment)collectorDataEntries[0].Attachments[0]).Uri.OriginalString); Assert.AreEqual($@"{Environment.MachineName}{Path.DirectorySeparatorChar}123[1].coverage", ((ObjectModel.UriDataAttachment)collectorDataEntries[0].Attachments[1]).Uri.OriginalString); @@ -181,7 +181,7 @@ public void ToResultFilesShouldAddAttachmentsWithRelativeUri() attachmentSets[0].Attachments.Add(uriDataAttachment1); var resultFiles = _converter.ToResultFiles(attachmentSets, testRun, @"c:\temp", null!); - Assert.IsTrue(resultFiles[0].Contains("abc.txt")); + Assert.Contains("abc.txt", resultFiles[0]); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/Build.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/Build.cs index e560d1818c..9b8b0c0e12 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/Build.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/Build.cs @@ -7,7 +7,7 @@ namespace Microsoft.TestPlatform.Library.IntegrationTests; [TestClass] -public class Build : IntegrationTestBase +public static class Build { [AssemblyInitialize] public static void AssemblyInitialize(TestContext testContext) diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/DeprecateExtensionsPathWarningTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/DeprecateExtensionsPathWarningTests.cs index 62efc3a9a4..df8ef1f114 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/DeprecateExtensionsPathWarningTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/DeprecateExtensionsPathWarningTests.cs @@ -9,7 +9,6 @@ namespace Microsoft.TestPlatform.Library.IntegrationTests; -[TestClass] [TestCategory("Windows-Review")] // TODO: but where are some tests? :D public class DeprecateExtensionsPathWarningTests : AcceptanceTestBase diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/DiaSessionTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/DiaSessionTests.cs index eebcd8ed39..b9f01f13dd 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/DiaSessionTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/DiaSessionTests.cs @@ -35,7 +35,7 @@ public void GetNavigationDataShouldReturnCorrectFileNameAndLineNumber() DiaNavigationData? diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "PassingTest"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); - StringAssert.EndsWith(diaNavigationData.FileName!.Replace("\\", "/"), @"\SimpleClassLibrary\Class1.cs".Replace("\\", "/")); + Assert.EndsWith(@"\SimpleClassLibrary\Class1.cs".Replace("\\", "/"), diaNavigationData.FileName!.Replace("\\", "/")); SourceAssert.LineIsAtMethodBodyStart(diaNavigationData.FileName!, "PassingTest", diaNavigationData.MinLineNumber, "Incorrect min line number"); @@ -52,7 +52,7 @@ public void GetNavigationDataShouldReturnCorrectDataForAsyncMethod() DiaNavigationData? diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1+d__1", "MoveNext"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); - StringAssert.EndsWith(diaNavigationData.FileName!.Replace("\\", "/"), @"\SimpleClassLibrary\Class1.cs".Replace("\\", "/")); + Assert.EndsWith(@"\SimpleClassLibrary\Class1.cs".Replace("\\", "/"), diaNavigationData.FileName!.Replace("\\", "/")); // The async state machine's MoveNext maps back to the original async method source lines. SourceAssert.LineIsAtMethodBodyStart(diaNavigationData.FileName!, "AsyncTestMethod", diaNavigationData.MinLineNumber, "Incorrect min line number"); @@ -70,9 +70,9 @@ public void GetNavigationDataShouldReturnCorrectDataForOverLoadedMethod() DiaNavigationData? diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "OverLoadedMethod"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); - StringAssert.EndsWith(diaNavigationData.FileName!.Replace("\\", "/"), @"\SimpleClassLibrary\Class1.cs".Replace("\\", "/")); + Assert.EndsWith(@"\SimpleClassLibrary\Class1.cs".Replace("\\", "/"), diaNavigationData.FileName!.Replace("\\", "/")); - // DiaSession may return any overload; verify min line falls within one of them. + // DiaSession may return any overload;verify min line falls within one of them. SourceAssert.LineIsAtMethodBodyStart(diaNavigationData.FileName!, "OverLoadedMethod", diaNavigationData.MinLineNumber, $"Min line number ({diaNavigationData.MinLineNumber}) is not at the body start of any OverLoadedMethod overload."); @@ -111,12 +111,12 @@ public void DiaSessionPerfTest() watch.Stop(); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); - StringAssert.EndsWith(diaNavigationData.FileName!.Replace("\\", "/"), @"\SimpleClassLibrary\HugeMethodSet.cs".Replace("\\", "/")); + Assert.EndsWith(@"\SimpleClassLibrary\HugeMethodSet.cs".Replace("\\", "/"), diaNavigationData.FileName!.Replace("\\", "/")); SourceAssert.LineIsAtMethodBodyStart(diaNavigationData.FileName!, "MSTest_D1_01", diaNavigationData.MinLineNumber, "Incorrect min line number"); var expectedTime = 150; - Assert.IsTrue(watch.Elapsed.Milliseconds < expectedTime, $"DiaSession Perf test Actual time:{watch.Elapsed.Milliseconds} ms Expected time:{expectedTime} ms"); + Assert.IsLessThan(expectedTime, watch.Elapsed.Milliseconds, $"DiaSession Perf test Actual time:{watch.Elapsed.Milliseconds} ms Expected time:{expectedTime} ms"); _testEnvironment.TargetFramework = currentTargetFrameWork; } diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/MetadataReaderHelperTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/MetadataReaderHelperTests.cs index 8e1e40ab3f..773b46a0b5 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/MetadataReaderHelperTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/MetadataReaderHelperTests.cs @@ -19,9 +19,9 @@ public void MetadataReaderHelper_GetCollectorExtensionTypes() var dataCollectorFilePath = GetTestDllForFramework("AttachmentProcessorDataCollector.dll", "netstandard2.0"); var types = MetadataReaderExtensionsHelper.DiscoverTestExtensionTypesV2Attribute(Assembly.LoadFile(dataCollectorFilePath), dataCollectorFilePath); Assert.IsTrue(types.Any(), $"File {dataCollectorFilePath}"); - Assert.IsTrue(types[0].AssemblyQualifiedName!.StartsWith("AttachmentProcessorDataCollector.SampleDataCollectorV2"), $"File {dataCollectorFilePath}"); + Assert.StartsWith("AttachmentProcessorDataCollector.SampleDataCollectorV2", types[0].AssemblyQualifiedName!, $"File {dataCollectorFilePath}"); Assert.AreEqual(dataCollectorFilePath.Replace("/", @"\"), types[0].Assembly.Location.Replace("/", @"\"), $"File {dataCollectorFilePath}"); - Assert.IsTrue(types[1].AssemblyQualifiedName!.StartsWith("AttachmentProcessorDataCollector.SampleDataCollectorV1"), $"File {dataCollectorFilePath}"); + Assert.StartsWith("AttachmentProcessorDataCollector.SampleDataCollectorV1", types[1].AssemblyQualifiedName!, $"File {dataCollectorFilePath}"); Assert.AreEqual(dataCollectorFilePath.Replace("/", @"\"), types[1].Assembly.Location.Replace("/", @"\"), $"File {dataCollectorFilePath}"); } } diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/CodeCoverageTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/CodeCoverageTests.cs index f0115525f0..a857826d73 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/CodeCoverageTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/CodeCoverageTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; @@ -61,11 +61,11 @@ public void TestRunWithCodeCoverage(RunnerInfo runnerInfo) new TestPlatformOptions { CollectMetrics = true }, null, _runEventHandler, _telemetryEventsHandler); // assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); int expectedNumberOfAttachments = 1; - Assert.AreEqual(expectedNumberOfAttachments, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); - Assert.IsTrue(_telemetryEventsHandler.Events.Any(e => e.Name.StartsWith("vs/codecoverage") && e.Properties.Any())); + Assert.HasCount(expectedNumberOfAttachments, _runEventHandler.Attachments, _runEventHandler.ToString()); + Assert.IsNotEmpty(_telemetryEventsHandler.Events.Where(e => e.Name.StartsWith("vs/codecoverage") && e.Properties.Any())); AssertCoverageResults(_runEventHandler.Attachments); @@ -86,11 +86,11 @@ public void TestRunWithCodeCoverageUsingClrIe(RunnerInfo runnerInfo) new TestPlatformOptions { CollectMetrics = true }, null, _runEventHandler, _telemetryEventsHandler); // assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.IsTrue(_telemetryEventsHandler.Events.Any(e => e.Name.StartsWith("vs/codecoverage") && e.Properties.Any())); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.IsNotEmpty(_telemetryEventsHandler.Events.Where(e => e.Name.StartsWith("vs/codecoverage") && e.Properties.Any())); int expectedNumberOfAttachments = 1; - Assert.AreEqual(expectedNumberOfAttachments, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); + Assert.HasCount(expectedNumberOfAttachments, _runEventHandler.Attachments, _runEventHandler.ToString()); AssertCoverageResults(_runEventHandler.Attachments); @@ -111,9 +111,9 @@ public void TestRunWithCodeCoverageParallel(RunnerInfo runnerInfo) new TestPlatformOptions { CollectMetrics = true }, null, _runEventHandler, _telemetryEventsHandler); // assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); - Assert.IsTrue(_telemetryEventsHandler.Events.Any(e => e.Name.StartsWith("vs/codecoverage") && e.Properties.Any())); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.Attachments, _runEventHandler.ToString()); + Assert.IsNotEmpty(_telemetryEventsHandler.Events.Where(e => e.Name.StartsWith("vs/codecoverage") && e.Properties.Any())); AssertCoverageResults(_runEventHandler.Attachments); @@ -140,9 +140,9 @@ private async Task TestRunWithCodeCoverageAndAttachmentsProcessingInternal(Runne _vstestConsoleWrapper.RunTests(GetTestAssemblies().Take(1), GetCodeCoverageRunSettings(1), null, null, _runEventHandler, _telemetryEventsHandler); _vstestConsoleWrapper.RunTests(GetTestAssemblies().Skip(1), GetCodeCoverageRunSettings(1), null, null, _runEventHandler, _telemetryEventsHandler); - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(2, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); - Assert.AreEqual(2, _runEventHandler.InvokedDataCollectors.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.Attachments, _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.InvokedDataCollectors, _runEventHandler.ToString()); Assert.IsFalse(_telemetryEventsHandler.Events.Any()); // act @@ -156,7 +156,7 @@ await _vstestConsoleWrapper.ProcessTestRunAttachmentsAsync( // Assert _testRunAttachmentsProcessingEventHandler.EnsureSuccess(); - Assert.AreEqual(1, _testRunAttachmentsProcessingEventHandler.Attachments.Count); + Assert.ContainsSingle(_testRunAttachmentsProcessingEventHandler.Attachments); AssertCoverageResults(_testRunAttachmentsProcessingEventHandler.Attachments); @@ -167,7 +167,7 @@ await _vstestConsoleWrapper.ProcessTestRunAttachmentsAsync( { TestRunAttachmentsProcessingProgressEventArgs progressArgs = _testRunAttachmentsProcessingEventHandler.ProgressArgs[i]; Assert.AreEqual(i + 1, progressArgs.CurrentAttachmentProcessorIndex); - Assert.AreEqual(1, progressArgs.CurrentAttachmentProcessorUris.Count); + Assert.ContainsSingle(progressArgs.CurrentAttachmentProcessorUris); Assert.AreEqual("datacollector://microsoft/CodeCoverage/2.0", progressArgs.CurrentAttachmentProcessorUris.First().AbsoluteUri); Assert.AreEqual(withInvokedDataCollectors ? 2 : 1, progressArgs.AttachmentProcessorsCount); if (_testRunAttachmentsProcessingEventHandler.ProgressArgs.Count == 2) @@ -197,9 +197,9 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingNoMetrics(Runne _vstestConsoleWrapper.RunTests(GetTestAssemblies().Take(1), GetCodeCoverageRunSettings(1), null, null, _runEventHandler, _telemetryEventsHandler); _vstestConsoleWrapper.RunTests(GetTestAssemblies().Skip(1), GetCodeCoverageRunSettings(1), null, null, _runEventHandler, _telemetryEventsHandler); - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(2, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); - Assert.AreEqual(2, _runEventHandler.InvokedDataCollectors.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.Attachments, _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.InvokedDataCollectors, _runEventHandler.ToString()); Assert.IsFalse(_telemetryEventsHandler.Events.Any()); // act @@ -212,7 +212,7 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingNoMetrics(Runne @"Microsoft\.VisualStudio\.Coverage\.DynamicCoverageDataCollectorWithAttachmentProcessorAndTelemetry, Microsoft\.VisualStudio\.TraceDataCollector, Version=.*, Culture=neutral, PublicKeyToken=.*")); _testRunAttachmentsProcessingEventHandler.EnsureSuccess(); - Assert.AreEqual(1, _testRunAttachmentsProcessingEventHandler.Attachments.Count); + Assert.ContainsSingle(_testRunAttachmentsProcessingEventHandler.Attachments); AssertCoverageResults(_testRunAttachmentsProcessingEventHandler.Attachments); @@ -223,7 +223,7 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingNoMetrics(Runne { TestRunAttachmentsProcessingProgressEventArgs progressArgs = _testRunAttachmentsProcessingEventHandler.ProgressArgs[i]; Assert.AreEqual(i + 1, progressArgs.CurrentAttachmentProcessorIndex); - Assert.AreEqual(1, progressArgs.CurrentAttachmentProcessorUris.Count); + Assert.ContainsSingle(progressArgs.CurrentAttachmentProcessorUris); Assert.AreEqual("datacollector://microsoft/CodeCoverage/2.0", progressArgs.CurrentAttachmentProcessorUris.First().AbsoluteUri); Assert.AreEqual(2, progressArgs.AttachmentProcessorsCount); if (_testRunAttachmentsProcessingEventHandler.ProgressArgs.Count == 2) @@ -251,9 +251,9 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingModuleDuplicate _vstestConsoleWrapper.RunTests(GetTestAssemblies().Skip(1), GetCodeCoverageRunSettings(1), null, null, _runEventHandler, _telemetryEventsHandler); _vstestConsoleWrapper.RunTests(GetTestAssemblies().Skip(1), GetCodeCoverageRunSettings(1), null, null, _runEventHandler, _telemetryEventsHandler); - Assert.AreEqual(9, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(3, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); - Assert.AreEqual(3, _runEventHandler.InvokedDataCollectors.Count, _runEventHandler.ToString()); + Assert.HasCount(9, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.HasCount(3, _runEventHandler.Attachments, _runEventHandler.ToString()); + Assert.HasCount(3, _runEventHandler.InvokedDataCollectors, _runEventHandler.ToString()); Assert.IsFalse(_telemetryEventsHandler.Events.Any()); // act @@ -266,7 +266,7 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingModuleDuplicate @"Microsoft\.VisualStudio\.Coverage\.DynamicCoverageDataCollectorWithAttachmentProcessorAndTelemetry, Microsoft\.VisualStudio\.TraceDataCollector, Version=.*, Culture=neutral, PublicKeyToken=.*")); _testRunAttachmentsProcessingEventHandler.EnsureSuccess(); - Assert.AreEqual(1, _testRunAttachmentsProcessingEventHandler.Attachments.Count); + Assert.ContainsSingle(_testRunAttachmentsProcessingEventHandler.Attachments); AssertCoverageResults(_testRunAttachmentsProcessingEventHandler.Attachments); @@ -312,9 +312,9 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingSameReportForma _vstestConsoleWrapper.RunTests(GetTestAssemblies().Skip(1), GetCodeCoverageRunSettings(1, outputFormat: "Coverage"), null, null, _runEventHandler, _telemetryEventsHandler); - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(2, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); - Assert.AreEqual(2, _runEventHandler.InvokedDataCollectors.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.Attachments, _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.InvokedDataCollectors, _runEventHandler.ToString()); Assert.IsFalse(_telemetryEventsHandler.Events.Any()); // act @@ -327,9 +327,9 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingSameReportForma @"Microsoft\.VisualStudio\.Coverage\.DynamicCoverageDataCollectorWithAttachmentProcessorAndTelemetry, Microsoft\.VisualStudio\.TraceDataCollector, Version=.*, Culture=neutral, PublicKeyToken=.*")); _testRunAttachmentsProcessingEventHandler.EnsureSuccess(); - Assert.AreEqual(1, _testRunAttachmentsProcessingEventHandler.Attachments.Count); - Assert.AreEqual(1, _testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments.Count); - Assert.IsTrue(_testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments[0].Uri.LocalPath.Contains(".coverage")); + Assert.ContainsSingle(_testRunAttachmentsProcessingEventHandler.Attachments); + Assert.ContainsSingle(_testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments); + Assert.Contains(".coverage", _testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments[0].Uri.LocalPath); AssertCoverageResults(_testRunAttachmentsProcessingEventHandler.Attachments); @@ -371,9 +371,9 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingDifferentReport _vstestConsoleWrapper.RunTests(GetTestAssemblies().Take(1), GetCodeCoverageRunSettings(1, outputFormat: "Cobertura"), null, null, _runEventHandler, _telemetryEventsHandler); _vstestConsoleWrapper.RunTests(GetTestAssemblies().Skip(1), GetCodeCoverageRunSettings(1, outputFormat: "Cobertura"), null, null, _runEventHandler, _telemetryEventsHandler); - Assert.AreEqual(12, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(4, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); - Assert.AreEqual(4, _runEventHandler.InvokedDataCollectors.Count, _runEventHandler.ToString()); + Assert.HasCount(12, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.HasCount(4, _runEventHandler.Attachments, _runEventHandler.ToString()); + Assert.HasCount(4, _runEventHandler.InvokedDataCollectors, _runEventHandler.ToString()); Assert.IsFalse(_telemetryEventsHandler.Events.Any()); // act @@ -387,10 +387,10 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingDifferentReport _testRunAttachmentsProcessingEventHandler.EnsureSuccess(); - Assert.AreEqual(1, _testRunAttachmentsProcessingEventHandler.Attachments.Count); - Assert.AreEqual(2, _testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments.Count); - Assert.IsTrue(_testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments[0].Uri.LocalPath.Contains(".cobertura.xml")); - Assert.IsTrue(_testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments[1].Uri.LocalPath.Contains(".coverage")); + Assert.ContainsSingle(_testRunAttachmentsProcessingEventHandler.Attachments); + Assert.HasCount(2, _testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments); + Assert.Contains(".cobertura.xml", _testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments[0].Uri.LocalPath); + Assert.Contains(".coverage", _testRunAttachmentsProcessingEventHandler.Attachments[0].Attachments[1].Uri.LocalPath); AssertCoverageResults(_testRunAttachmentsProcessingEventHandler.Attachments); @@ -431,9 +431,9 @@ public async Task EndSessionShouldEnsureVstestConsoleProcessDies(RunnerInfo runn _vstestConsoleWrapper.RunTests(GetTestAssemblies().Take(1), GetCodeCoverageRunSettings(1), null, null, _runEventHandler, _telemetryEventsHandler); _vstestConsoleWrapper.RunTests(GetTestAssemblies().Skip(1), GetCodeCoverageRunSettings(1), null, null, _runEventHandler, _telemetryEventsHandler); - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(2, _runEventHandler.Attachments.Count, _runEventHandler.ToString()); - Assert.AreEqual(2, _runEventHandler.InvokedDataCollectors.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.Attachments, _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.InvokedDataCollectors, _runEventHandler.ToString()); Assert.IsFalse(_telemetryEventsHandler.Events.Any()); await _vstestConsoleWrapper.ProcessTestRunAttachmentsAsync(_runEventHandler.Attachments, _runEventHandler.InvokedDataCollectors, GetCodeCoverageRunSettings(1), true, true, _testRunAttachmentsProcessingEventHandler, CancellationToken.None); diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/DifferentTestFrameworkSimpleTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/DifferentTestFrameworkSimpleTests.cs index f8458247bb..23ebdf9ca3 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/DifferentTestFrameworkSimpleTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/DifferentTestFrameworkSimpleTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; @@ -56,12 +56,12 @@ public void RunTestsWithNunitAdapter(RunnerInfo runnerInfo) _runEventHandler); var testResult = _runEventHandler.TestResults.Where(tr => tr.TestCase.DisplayName.Equals("PassTestMethod1")).First(); - StringAssert.EndsWith(testResult.TestCase.FullyQualifiedName, "PassTestMethod1"); + Assert.EndsWith("PassTestMethod1", testResult.TestCase.FullyQualifiedName); // Assert - Assert.AreEqual(2, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults.Where(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults.Where(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); var nunitSourceFile = SourceAssert.FindSourceFile("NUTestProject.dll", "PassTestMethod1"); SourceAssert.LineIsAtMethodBodyStart(nunitSourceFile, "PassTestMethod1", testResult.TestCase.LineNumber); @@ -92,12 +92,12 @@ public void RunTestsWithXunitAdapter(RunnerInfo runnerInfo) _runEventHandler); var testResult = _runEventHandler.TestResults.Where(tr => tr.TestCase.DisplayName.Equals("xUnitTestProject.Class1.PassTestMethod1")).First(); - StringAssert.EndsWith(testResult.TestCase.FullyQualifiedName, "PassTestMethod1"); + Assert.EndsWith("PassTestMethod1", testResult.TestCase.FullyQualifiedName); // Assert - Assert.AreEqual(2, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults.Where(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults.Where(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); var xunitSourceFile = SourceAssert.FindSourceFile("XUTestProject.dll", "PassTestMethod1"); SourceAssert.LineIsAtMethodBodyStart(xunitSourceFile, "PassTestMethod1", testResult.TestCase.LineNumber); @@ -129,8 +129,8 @@ public void RunTestsWithNonDllAdapter(RunnerInfo runnerInfo) var testCase = _runEventHandler.TestResults.Where(tr => tr.TestCase.DisplayName.Equals("TestMethod1")); // Assert - Assert.AreEqual(1, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults.Where(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); Assert.AreEqual(0, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); } } diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/DiscoverTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/DiscoverTests.cs index a66c9147c8..5a96e743cd 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/DiscoverTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/DiscoverTests.cs @@ -58,7 +58,7 @@ public void DiscoverTestsUsingDiscoveryEventHandler1(RunnerInfo runnerInfo) _vstestConsoleWrapper.DiscoverTests(GetTestDlls("MSTestProject1.dll", "MSTestProject2.dll"), GetDefaultRunSettings(), _discoveryEventHandler); // Assert. - Assert.AreEqual(6, _discoveryEventHandler.DiscoveredTestCases.Count); + Assert.HasCount(6, _discoveryEventHandler.DiscoveredTestCases); } [TestMethod] @@ -80,8 +80,8 @@ public void DiscoverTestsUsingDiscoveryEventHandler2AndTelemetryOptedOut(RunnerI _discoveryEventHandler2); // Assert. - Assert.AreEqual(6, _discoveryEventHandler2.DiscoveredTestCases.Count); - Assert.AreEqual(0, _discoveryEventHandler2.Metrics!.Count); + Assert.HasCount(6, _discoveryEventHandler2.DiscoveredTestCases); + Assert.HasCount(0, _discoveryEventHandler2.Metrics!); } [TestMethod] @@ -96,7 +96,7 @@ public void DiscoverTestsUsingDiscoveryEventHandler2AndTelemetryOptedIn(RunnerIn _vstestConsoleWrapper.DiscoverTests(GetTestAssemblies(), GetDefaultRunSettings(), new TestPlatformOptions() { CollectMetrics = true }, _discoveryEventHandler2); // Assert. - Assert.AreEqual(6, _discoveryEventHandler2.DiscoveredTestCases.Count); + Assert.HasCount(6, _discoveryEventHandler2.DiscoveredTestCases); Assert.IsTrue(_discoveryEventHandler2.Metrics!.ContainsKey(TelemetryDataConstants.TargetDevice)); Assert.IsTrue(_discoveryEventHandler2.Metrics.ContainsKey(TelemetryDataConstants.NumberOfAdapterUsedToDiscoverTests)); Assert.IsTrue(_discoveryEventHandler2.Metrics.ContainsKey(TelemetryDataConstants.TimeTakenInSecByAllAdapters)); @@ -177,7 +177,7 @@ public void DiscoverTestUsingEventHandler2ShouldContainAllSourcesAsFullyDiscover eventHandler2); // Assert. - Assert.AreEqual(2, eventHandler2.FullyDiscoveredSources!.Count); + Assert.HasCount(2, eventHandler2.FullyDiscoveredSources!); } [TestMethod] @@ -198,7 +198,7 @@ public void DiscoverTestsUsingSourceNavigation(RunnerInfo runnerInfo) // Assert. var testCase = _discoveryEventHandler.DiscoveredTestCases.Where(dt => dt.FullyQualifiedName.Equals("SampleUnitTestProject.UnitTest1.PassingTest")).First(); - StringAssert.EndsWith(testCase.FullyQualifiedName, "PassingTest"); + Assert.EndsWith("PassingTest", testCase.FullyQualifiedName); var sourceFile = SourceAssert.FindSourceFile("SimpleTestProject.dll", "PassingTest"); SourceAssert.LineIsWithinMethod(sourceFile, "PassingTest", testCase.LineNumber); @@ -264,7 +264,7 @@ public async Task CancelTestDiscovery(RunnerInfo runnerInfo) // Act Console.WriteLine("Starting Discovery."); - await Task.Run(() => _vstestConsoleWrapper.DiscoverTests(testAssemblies, runSettingsXml, discoveryEvents.Object)); + await Task.Run(() => _vstestConsoleWrapper.DiscoverTests(testAssemblies, runSettingsXml, discoveryEvents.Object), TestContext.CancellationToken); Console.WriteLine("Discovery finished."); // Assert diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/LiveUnitTestingTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/LiveUnitTestingTests.cs index 6c5989c981..21afa15e53 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/LiveUnitTestingTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/LiveUnitTestingTests.cs @@ -57,7 +57,7 @@ public void DiscoverTestsUsingLiveUnitTesting(RunnerInfo runnerInfo) _discoveryEventHandler); // Assert - Assert.AreEqual(6, _discoveryEventHandler.DiscoveredTestCases.Count); + Assert.HasCount(6, _discoveryEventHandler.DiscoveredTestCases); } [TestMethod] @@ -82,7 +82,7 @@ public void RunTestsWithLiveUnitTesting(RunnerInfo runnerInfo) _runEventHandler); // Assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Skipped), _runEventHandler.ToString()); diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunSelectedTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunSelectedTests.cs index 5d1ff8608e..2357b9f7cc 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunSelectedTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunSelectedTests.cs @@ -49,7 +49,7 @@ public void RunSelectedTestsWithoutTestPlatformOptions(RunnerInfo runnerInfo) _vstestConsoleWrapper.RunTests(testCases, GetDefaultRunSettings(), _runEventHandler); // Assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Skipped), _runEventHandler.ToString()); @@ -72,7 +72,7 @@ public void RunSelectedTestsWithTestPlatformOptions(RunnerInfo runnerInfo) _runEventHandler); // Assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); Assert.IsTrue(_runEventHandler.Metrics!.ContainsKey(TelemetryDataConstants.TargetDevice)); Assert.IsTrue(_runEventHandler.Metrics.ContainsKey(TelemetryDataConstants.TargetFramework)); Assert.IsTrue(_runEventHandler.Metrics.ContainsKey(TelemetryDataConstants.TargetOS)); diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTests.cs index 99de315860..f60630186e 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTests.cs @@ -56,7 +56,7 @@ public void RunAllTests(RunnerInfo runnerInfo) _vstestConsoleWrapper.RunTests(GetTestDlls("MSTestProject1.dll", "MSTestProject2.dll"), GetDefaultRunSettings(), runEventHandler); // Assert - Assert.AreEqual(6, runEventHandler.TestResults.Count); + Assert.HasCount(6, runEventHandler.TestResults); Assert.AreEqual(2, runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed)); Assert.AreEqual(2, runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed)); Assert.AreEqual(2, runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Skipped)); @@ -75,7 +75,7 @@ public void RunAllTestsFromDlls(RunnerInfo runnerInfo) _vstestConsoleWrapper.RunTests([GetAssetFullPath("SimpleTestProject.dll"), GetAssetFullPath("SimpleTestProject2.dll")], GetDefaultRunSettings(), runEventHandler); // Assert - Assert.AreEqual(6, runEventHandler.TestResults.Count); + Assert.HasCount(6, runEventHandler.TestResults); Assert.AreEqual(2, runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed)); Assert.AreEqual(2, runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed)); Assert.AreEqual(2, runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Skipped)); @@ -141,7 +141,7 @@ public void RunTestsWithTelemetryOptedIn(RunnerInfo runnerInfo) _runEventHandler); // Assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); Assert.IsTrue(_runEventHandler.Metrics!.ContainsKey(TelemetryDataConstants.TargetDevice)); Assert.IsTrue(_runEventHandler.Metrics.ContainsKey(TelemetryDataConstants.TargetFramework)); Assert.IsTrue(_runEventHandler.Metrics.ContainsKey(TelemetryDataConstants.TargetOS)); @@ -164,8 +164,8 @@ public void RunTestsWithTelemetryOptedOut(RunnerInfo runnerInfo) _runEventHandler); // Assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(0, _runEventHandler.Metrics!.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.HasCount(0, _runEventHandler.Metrics!, _runEventHandler.ToString()); } [TestMethod] @@ -221,8 +221,8 @@ public void RunTestsShouldShowProperWarningOnNoTestsForTestCaseFilter(RunnerInfo var expectedFilter = veryLongTestCaseFilter.Substring(0, 256) + "..."; // Assert - StringAssert.StartsWith(_runEventHandler.LogMessage, $"No test matches the given testcase filter `{expectedFilter}` in"); - StringAssert.EndsWith(_runEventHandler.LogMessage, testAssemblyName); + Assert.StartsWith($"No test matches the given testcase filter `{expectedFilter}` in", _runEventHandler.LogMessage); + Assert.EndsWith(testAssemblyName, _runEventHandler.LogMessage); Assert.AreEqual(TestMessageLevel.Warning, _runEventHandler.TestMessageLevel); } diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTestsWithDifferentConfigurationTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTestsWithDifferentConfigurationTests.cs index e96b9dbfb5..9ac4c8f513 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTestsWithDifferentConfigurationTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTestsWithDifferentConfigurationTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; @@ -59,7 +59,7 @@ public void RunTestsWithTestAdapterPath(RunnerInfo runnerInfo) _runEventHandler); // Assert - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Skipped), _runEventHandler.ToString()); @@ -90,7 +90,7 @@ public void RunTestsWithRunSettingsWithParallel(RunnerInfo runnerInfo) // Assert _runEventHandler.EnsureSuccess(); - Assert.AreEqual(6, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); + Assert.HasCount(6, _runEventHandler.TestResults, _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); Assert.AreEqual(2, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Skipped), _runEventHandler.ToString()); @@ -120,8 +120,8 @@ public void RunTestsWithX64Source(RunnerInfo runnerInfo) _runEventHandler); // Assert - Assert.AreEqual(1, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults.Where(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); AssertExpectedNumberOfHostProcesses(expectedNumOfProcessCreated, _logsDir.Path, testhostProcessNames); } diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTestsWithFilterTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTestsWithFilterTests.cs index 23f2c507d0..decb300853 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTestsWithFilterTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/RunTestsWithFilterTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; @@ -55,7 +55,7 @@ public void RunTestsWithTestCaseFilter(RunnerInfo runnerInfo) _runEventHandler); // Assert - Assert.AreEqual(1, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults, _runEventHandler.ToString()); Assert.AreEqual(TestOutcome.Passed, _runEventHandler.TestResults.First().Outcome); } @@ -76,8 +76,8 @@ public void RunTestsWithFastFilter(RunnerInfo runnerInfo) _runEventHandler); // Assert - Assert.AreEqual(2, _runEventHandler.TestResults.Count, _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); - Assert.AreEqual(1, _runEventHandler.TestResults.Count(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); + Assert.HasCount(2, _runEventHandler.TestResults, _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults.Where(t => t.Outcome == TestOutcome.Passed), _runEventHandler.ToString()); + Assert.ContainsSingle(_runEventHandler.TestResults.Where(t => t.Outcome == TestOutcome.Failed), _runEventHandler.ToString()); } } diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/SerializeTestRunTests.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/SerializeTestRunTests.cs index 1265fa02a3..1c470a41b6 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/SerializeTestRunTests.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/SerializeTestRunTests.cs @@ -65,9 +65,9 @@ public void DiscoverTestsAndRunTestsSequentially(RunnerInfo runnerInfo) _runEventHandler.EnsureSuccess(); // Assert - Assert.AreEqual(10, _discoveryEventHandler.DiscoveredTestCases.Count); + Assert.HasCount(10, _discoveryEventHandler.DiscoveredTestCases); int failedTests = _runEventHandler.TestResults.Count(x => x.Outcome == TestOutcome.Failed); - Assert.IsFalse(failedTests > 0, $"Number of failed tests {failedTests}"); + Assert.AreEqual(0, failedTests, $"Number of failed tests {failedTests}"); } [TestMethod] @@ -88,9 +88,9 @@ public void DiscoverTestsAndRunTestsSequentially_DisabledByFeatureFlag(RunnerInf _runEventHandler.EnsureSuccess(); // Assert - Assert.AreEqual(10, _discoveryEventHandler.DiscoveredTestCases.Count); + Assert.HasCount(10, _discoveryEventHandler.DiscoveredTestCases); int failedTests = _runEventHandler.TestResults.Count(x => x.Outcome == TestOutcome.Failed); - Assert.IsTrue(failedTests > 0, $"Number of failed tests {failedTests}"); + Assert.IsGreaterThan(0, failedTests, $"Number of failed tests {failedTests}"); } [TestMethod] @@ -113,7 +113,7 @@ public void DiscoverTestsAndRunTestsSequentially_IsNotSupportedForSources(Runner builder.AppendLine(error); } - Assert.IsTrue(_runEventHandler.Errors.Count > 0, _runEventHandler.ToString()); - Assert.IsTrue(_runEventHandler.Errors.Contains(VisualStudio.TestPlatform.Common.Resources.Resources.SerialTestRunInvalidScenario), $"Error messages\n:{builder}"); + Assert.IsNotEmpty(_runEventHandler.Errors, _runEventHandler.ToString()); + Assert.Contains(VisualStudio.TestPlatform.Common.Resources.Resources.SerialTestRunInvalidScenario, _runEventHandler.Errors, $"Error messages\n:{builder}"); } } diff --git a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/TargetFrameworkTestHostDemultiplexer.cs b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/TargetFrameworkTestHostDemultiplexer.cs index 3477c7a056..bb553f04ca 100644 --- a/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/TargetFrameworkTestHostDemultiplexer.cs +++ b/test/Microsoft.TestPlatform.Library.IntegrationTests/TranslationLayerTests/TargetFrameworkTestHostDemultiplexer.cs @@ -84,12 +84,12 @@ private void ExecuteContainerInMultiHost(RunnerInfo runnerInfo, int expectedHost _runEventHandler.EnsureSuccess(); // Assert - Assert.AreEqual(10, _discoveryEventHandler.DiscoveredTestCases.Count); + Assert.HasCount(10, _discoveryEventHandler.DiscoveredTestCases); int failedTests = _runEventHandler.TestResults.Count(x => x.Outcome == TestOutcome.Failed); - Assert.IsFalse(failedTests > 0, $"Number of failed tests {failedTests}"); + Assert.IsLessThanOrEqualTo(0, failedTests, $"Number of failed tests {failedTests}"); string[] hosts = Directory.GetFiles(TempDirectory.Path, "TestHost*"); - Assert.AreEqual(expectedHost == -1 ? 1 : expectedHost > 10 ? 10 : expectedHost, hosts.Length); + Assert.HasCount(expectedHost == -1 ? 1 : expectedHost > 10 ? 10 : expectedHost, hosts); List tests = new(); int testsRunInsideHost; @@ -111,15 +111,15 @@ private void ExecuteContainerInMultiHost(RunnerInfo runnerInfo, int expectedHost if (expectedHost == 3) { - Assert.IsTrue(testsRunInsideHost >= 3); + Assert.IsGreaterThanOrEqualTo(3, testsRunInsideHost); } } - Assert.AreEqual(10, tests.Count); + Assert.HasCount(10, tests); for (int i = 1; i <= 10; i++) { tests.Remove($"TestMethod{i}"); } - Assert.AreEqual(0, tests.Count); + Assert.IsEmpty(tests); } } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Client/BaseTestRunCriteriaTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Client/BaseTestRunCriteriaTests.cs index cead712f27..1567335e6d 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Client/BaseTestRunCriteriaTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Client/BaseTestRunCriteriaTests.cs @@ -14,54 +14,21 @@ public class BaseTestRunCriteriaTests [TestMethod] public void ConstructorShouldThrowIfFrequencyOfRunStatsChangeIsZero() { - var isExceptionThrown = false; - - try - { - var criteria = new BaseTestRunCriteria(frequencyOfRunStatsChangeEvent: 0); - } - catch (ArgumentOutOfRangeException ex) - { - isExceptionThrown = true; - StringAssert.Contains(ex.Message, "Notification frequency need to be a positive value."); - } - - Assert.IsTrue(isExceptionThrown); + var ex = Assert.ThrowsExactly(() => new BaseTestRunCriteria(frequencyOfRunStatsChangeEvent: 0)); + Assert.Contains("Notification frequency need to be a positive value.", ex.Message); } [TestMethod] public void ConstructorShouldThrowIfFrequencyOfRunStatsChangeIsLesssThanZero() { - var isExceptionThrown = false; - - try - { - var criteria = new BaseTestRunCriteria(frequencyOfRunStatsChangeEvent: -10); - } - catch (ArgumentOutOfRangeException ex) - { - isExceptionThrown = true; - StringAssert.Contains(ex.Message, "Notification frequency need to be a positive value."); - } - - Assert.IsTrue(isExceptionThrown); + var ex = Assert.ThrowsExactly(() => new BaseTestRunCriteria(frequencyOfRunStatsChangeEvent: -10)); + Assert.Contains("Notification frequency need to be a positive value.", ex.Message); } [TestMethod] public void ConstructorShouldThrowIfRunStatsChangeEventTimeoutIsMinimumTimeSpanValue() { - var isExceptionThrown = false; - - try - { - var criteria = new BaseTestRunCriteria(frequencyOfRunStatsChangeEvent: 1, keepAlive: false, testSettings: null, runStatsChangeEventTimeout: TimeSpan.MinValue); - } - catch (ArgumentOutOfRangeException ex) - { - isExceptionThrown = true; - StringAssert.Contains(ex.Message, "Notification timeout must be greater than zero."); - } - - Assert.IsTrue(isExceptionThrown); + var ex = Assert.ThrowsExactly(() => new BaseTestRunCriteria(frequencyOfRunStatsChangeEvent: 1, keepAlive: false, testSettings: null, runStatsChangeEventTimeout: TimeSpan.MinValue)); + Assert.Contains("Notification timeout must be greater than zero.", ex.Message); } } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/CustomKeyValueConverterTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/CustomKeyValueConverterTests.cs index 804cf98ce2..8692d0361b 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/CustomKeyValueConverterTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/CustomKeyValueConverterTests.cs @@ -28,7 +28,7 @@ public void CustomKeyValueConverterShouldDeserializeWellformedJson() var data = _customKeyValueConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as KeyValuePair[]; Assert.IsNotNull(data); - Assert.AreEqual(1, data.Length); + Assert.HasCount(1, data); Assert.AreEqual("key1", data[0].Key); Assert.AreEqual("val1", data[0].Value); } @@ -41,7 +41,7 @@ public void CustomKeyValueConverterShouldDeserializeKeyValuePairArray() var data = _customKeyValueConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as KeyValuePair[]; Assert.IsNotNull(data); - Assert.AreEqual(2, data.Length); + Assert.HasCount(2, data); Assert.AreEqual("key1", data[0].Key); Assert.AreEqual("val1", data[0].Value); Assert.AreEqual("key2", data[1].Key); @@ -56,7 +56,7 @@ public void CustomKeyValueConverterShouldDeserializeEmptyArray() var data = _customKeyValueConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as KeyValuePair[]; Assert.IsNotNull(data); - Assert.AreEqual(0, data.Length); + Assert.IsEmpty(data); } [TestMethod] @@ -67,7 +67,7 @@ public void CustomKeyValueConverterShouldDeserializeEmptyKeyOrValue() var data = _customKeyValueConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as KeyValuePair[]; Assert.IsNotNull(data); - Assert.AreEqual(1, data.Length); + Assert.HasCount(1, data); Assert.AreEqual(string.Empty, data[0].Key); Assert.AreEqual(string.Empty, data[0].Value); } @@ -80,7 +80,7 @@ public void CustomKeyValueConverterShouldDeserializeDuplicateKeysKvps() var data = _customKeyValueConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as KeyValuePair[]; Assert.IsNotNull(data); - Assert.AreEqual(2, data.Length); + Assert.HasCount(2, data); Assert.AreEqual("key1", data[0].Key); Assert.AreEqual("val1", data[0].Value); Assert.AreEqual("key1", data[1].Key); diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/CustomStringArrayConverterTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/CustomStringArrayConverterTests.cs index 3e235f3792..eaac20df33 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/CustomStringArrayConverterTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/CustomStringArrayConverterTests.cs @@ -27,7 +27,7 @@ public void CustomStringArrayConverterShouldDeserializeWellformedJson() var data = _customStringArrayConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as string[]; Assert.IsNotNull(data); - Assert.AreEqual(2, data.Length); + Assert.HasCount(2, data); CollectionAssert.AreEqual(new[] { "val2", "val1" }, data); } @@ -39,7 +39,7 @@ public void CustomStringArrayConverterShouldDeserializeEmptyArray() var data = _customStringArrayConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as string[]; Assert.IsNotNull(data); - Assert.AreEqual(0, data.Length); + Assert.IsEmpty(data); } [TestMethod] @@ -50,7 +50,7 @@ public void CustomStringArrayConverterShouldDeserializeNullKeyOrValue() var data = _customStringArrayConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as string[]; Assert.IsNotNull(data); - Assert.AreEqual(2, data.Length); + Assert.HasCount(2, data); Assert.IsNull(data[0]); Assert.AreEqual("val", data[1]); } @@ -63,7 +63,7 @@ public void CustomStringArrayConverterShouldDeserializeEmptyKeyOrValue() var data = _customStringArrayConverter.ConvertFrom(null, CultureInfo.InvariantCulture, json) as string[]; Assert.IsNotNull(data); - Assert.AreEqual(2, data.Length); + Assert.HasCount(2, data); Assert.AreEqual(string.Empty, data[0]); Assert.AreEqual(string.Empty, data[1]); } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Hosting/TestRunnerConnectionInfoExtensionsTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Hosting/TestRunnerConnectionInfoExtensionsTests.cs index abdc716457..37bdd0a664 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Hosting/TestRunnerConnectionInfoExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Hosting/TestRunnerConnectionInfoExtensionsTests.cs @@ -18,7 +18,7 @@ public void ToCommandLineOptionsShouldIncludePort() var options = connectionInfo.ToCommandLineOptions(); - StringAssert.StartsWith(options, "--port 123 --endpoint 127.0.0.0:123 --role client"); + Assert.StartsWith("--port 123 --endpoint 127.0.0.0:123 --role client", options); } [TestMethod] @@ -28,7 +28,7 @@ public void ToCommandLineOptionsShouldIncludeEndpoint() var options = connectionInfo.ToCommandLineOptions(); - StringAssert.Contains(options, "--endpoint 127.0.0.0:123"); + Assert.Contains("--endpoint 127.0.0.0:123", options); } [TestMethod] @@ -38,7 +38,7 @@ public void ToCommandLineOptionsShouldIncludeRole() var options = connectionInfo.ToCommandLineOptions(); - StringAssert.Contains(options, "--role client"); + Assert.Contains("--role client", options); } [TestMethod] @@ -48,7 +48,7 @@ public void ToCommandLineOptionsShouldIncludeParentProcessId() var options = connectionInfo.ToCommandLineOptions(); - Assert.IsTrue(options.IndexOf("--parentprocessid 123", StringComparison.OrdinalIgnoreCase) >= 0); + Assert.IsGreaterThanOrEqualTo(0, options.IndexOf("--parentprocessid 123", StringComparison.OrdinalIgnoreCase)); } [TestMethod] @@ -58,7 +58,7 @@ public void ToCommandLineOptionsShouldNotIncludeDiagnosticsOptionIfNotEnabled() var options = connectionInfo.ToCommandLineOptions(); - Assert.IsFalse(options.IndexOf("--diag", StringComparison.OrdinalIgnoreCase) >= 0); + Assert.IsLessThan(0, options.IndexOf("--diag", StringComparison.OrdinalIgnoreCase)); } [TestMethod] @@ -68,6 +68,6 @@ public void ToCommandLineOptionsShouldIncludeDiagnosticsOptionIfEnabled() var options = connectionInfo.ToCommandLineOptions(); - StringAssert.EndsWith(options, "--diag log.txt --tracelevel 3"); + Assert.EndsWith("--diag log.txt --tracelevel 3", options); } } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs index d01730b060..b3a9f86ba8 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs @@ -280,7 +280,7 @@ public void RunConfigurationToXmlShouldProvideDesignMode() { var runConfiguration = new RunConfiguration { DesignMode = true }; - StringAssert.Contains(runConfiguration.ToXml().InnerXml, "True"); + Assert.Contains("True", runConfiguration.ToXml().InnerXml); } [DataRow(true)] @@ -324,7 +324,7 @@ public void RunConfigurationShouldSetCollectSourceInformationSameAsDesignModeByD public void RunConfigurationToXmlShouldProvideCollectSourceInformationSameAsDesignMode(bool val) { var runConfiguration = new RunConfiguration { DesignMode = val }; - StringAssert.Contains(runConfiguration.ToXml().InnerXml.ToUpperInvariant(), $"{val}".ToUpperInvariant()); + Assert.Contains($"{val}".ToUpperInvariant(), runConfiguration.ToXml().InnerXml.ToUpperInvariant()); } [TestMethod] @@ -332,7 +332,7 @@ public void RunConfigurationToXmlShouldProvideExecutionThreadApartmentState() { var runConfiguration = new RunConfiguration { ExecutionThreadApartmentState = PlatformApartmentState.STA }; - StringAssert.Contains(runConfiguration.ToXml().InnerXml, "STA"); + Assert.Contains("STA", runConfiguration.ToXml().InnerXml); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestObjectTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestObjectTests.cs index 51278d94ea..3980e88d1e 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestObjectTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestObjectTests.cs @@ -41,6 +41,6 @@ public void GetPropertiesShouldReturnListOfPropertiesInStore() TestCase.SetPropertyValue(kvp.Key, kvp.Value); var properties = TestCase.GetProperties().ToList(); - Assert.IsTrue(properties.Contains(kvp)); + Assert.Contains(kvp, properties); } } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestResultTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestResultTests.cs index a6219cc386..6951e1d274 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestResultTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestResultTests.cs @@ -25,20 +25,20 @@ public TestResultTests() [TestMethod] public void TestResultShouldInitializeEmptyAttachments() { - Assert.AreEqual(0, _result.Attachments.Count); + Assert.IsEmpty(_result.Attachments); } [TestMethod] public void TestResultShouldInitializeEmptyMessages() { - Assert.AreEqual(0, _result.Messages.Count); + Assert.IsEmpty(_result.Messages); } [TestMethod] public void TestResultShouldInitializeStartAndEndTimeToCurrent() { - Assert.IsTrue(_result.StartTime.Subtract(DateTimeOffset.UtcNow) < new TimeSpan(0, 0, 0, 10)); - Assert.IsTrue(_result.EndTime.Subtract(DateTimeOffset.UtcNow) < new TimeSpan(0, 0, 0, 10)); + Assert.IsLessThan(new TimeSpan(0, 0, 0, 10), _result.StartTime.Subtract(DateTimeOffset.UtcNow)); + Assert.IsLessThan(new TimeSpan(0, 0, 0, 10), _result.EndTime.Subtract(DateTimeOffset.UtcNow)); } #region GetSetPropertyValue Tests diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs index 61a851b338..56461df75d 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs @@ -90,7 +90,7 @@ public void GetTestRunParametersReturnsEmptyDictionaryOnNullRunSettings() { Dictionary trp = XmlRunSettingsUtilities.GetTestRunParameters(null); Assert.IsNotNull(trp); - Assert.AreEqual(0, trp.Count); + Assert.IsEmpty(trp); } [TestMethod] @@ -108,7 +108,7 @@ public void GetTestRunParametersReturnsEmptyDictionaryWhenNoTestRunParameters() Dictionary trp = XmlRunSettingsUtilities.GetTestRunParameters(settingsXml); Assert.IsNotNull(trp); - Assert.AreEqual(0, trp.Count); + Assert.IsEmpty(trp); } [TestMethod] @@ -128,7 +128,7 @@ public void GetTestRunParametersReturnsEmptyDictionaryForEmptyTestRunParametersN Dictionary trp = XmlRunSettingsUtilities.GetTestRunParameters(settingsXml); Assert.IsNotNull(trp); - Assert.AreEqual(0, trp.Count); + Assert.IsEmpty(trp); } [TestMethod] @@ -149,7 +149,7 @@ public void GetTestRunParametersReturns1EntryOn1TestRunParameter() Dictionary trp = XmlRunSettingsUtilities.GetTestRunParameters(settingsXml); Assert.IsNotNull(trp); - Assert.AreEqual(1, trp.Count); + Assert.HasCount(1, trp); // Verify Parameter Values. Assert.IsTrue(trp.ContainsKey("webAppUrl")); @@ -176,7 +176,7 @@ public void GetTestRunParametersReturns3EntryOn3TestRunParameter() Dictionary trp = XmlRunSettingsUtilities.GetTestRunParameters(settingsXml); Assert.IsNotNull(trp); - Assert.AreEqual(3, trp.Count); + Assert.HasCount(3, trp); // Verify Parameter Values. Assert.IsTrue(trp.ContainsKey("webAppUrl")); @@ -244,7 +244,7 @@ public void GetTestRunParametersIgnoresMalformedKeyValues() Dictionary trp = XmlRunSettingsUtilities.GetTestRunParameters(settingsXml); Assert.IsNotNull(trp); - Assert.AreEqual(0, trp.Count); + Assert.IsEmpty(trp); } [TestMethod] @@ -263,7 +263,7 @@ public void GetInProcDataCollectionRunSettingsFromSettings() "; var inProcDcRunSettings = XmlRunSettingsUtilities.GetInProcDataCollectionRunSettings(settingsXml); Assert.IsNotNull(inProcDcRunSettings); - Assert.AreEqual(1, inProcDcRunSettings.DataCollectorSettingsList.Count); + Assert.HasCount(1, inProcDcRunSettings.DataCollectorSettingsList); } [TestMethod] @@ -480,12 +480,13 @@ public void GetLoggerRunSettingsShouldThrowWhenInvalidUri() exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains( + Assert.Contains( string.Format( CultureInfo.CurrentCulture, Resources.InvalidUriInSettings, "invalidUri", - "Logger"))); + "Logger"), + exceptionMessage); } [TestMethod] @@ -609,7 +610,7 @@ public void GetLoggerRunSettingsShouldThrowIfDuplicateAttributesPresent() exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains(CommonResources.MalformedRunSettingsFile)); + Assert.Contains(CommonResources.MalformedRunSettingsFile, exceptionMessage); } [TestMethod] @@ -684,7 +685,7 @@ public void GetLoggerRunSettingsShouldThrowShouldThrowOnMalformedLoggerSettings( exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains(CommonResources.MalformedRunSettingsFile)); + Assert.Contains(CommonResources.MalformedRunSettingsFile, exceptionMessage); } [TestMethod] @@ -713,11 +714,11 @@ public void GetLoggerRunSettingsShouldThrowWhenAttribtuesPresentInLoggerRunSetti exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains(string.Format( + Assert.Contains(string.Format( CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlAttribute, "LoggerRunSettings", - "name"))); + "name"), exceptionMessage); } [TestMethod] @@ -733,7 +734,7 @@ public void GetLoggerRunSettingsShouldReturnEmptyLoggerRunSettingsWhenLoggerRunS "; var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggerRunSettingsNode)!; - Assert.AreEqual(0, loggerRunSettings.LoggerSettingsList.Count); + Assert.IsEmpty(loggerRunSettings.LoggerSettingsList); } [TestMethod] @@ -748,7 +749,7 @@ public void GetLoggerRunSettingsShouldReturnEmptyLoggerRunSettingsWhenLoggerRunS "; var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggerRunSettingsNode)!; - Assert.AreEqual(0, loggerRunSettings.LoggerSettingsList.Count); + Assert.IsEmpty(loggerRunSettings.LoggerSettingsList); } [TestMethod] @@ -777,11 +778,11 @@ public void GetLoggerRunSettingsShouldThrowWhenNodeOtherThanLoggersPresentInLogg exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains(string.Format( + Assert.Contains(string.Format( CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlElement, "LoggerRUNSettings", - "LoggersInvalid"))); + "LoggersInvalid"), exceptionMessage); } [TestMethod] @@ -810,11 +811,11 @@ public void GetLoggerRunSettingsShouldThrowWhenAttribtuesPresentInLoggersNode() exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains(string.Format( + Assert.Contains(string.Format( CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlAttribute, "Loggers", - "nameAttr"))); + "nameAttr"), exceptionMessage); } [TestMethod] @@ -832,7 +833,7 @@ public void GetLoggerRunSettingsShouldReturnEmptyLoggersWhenLoggersIsEmpty() "; var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggersNode)!; - Assert.AreEqual(0, loggerRunSettings.LoggerSettingsList.Count); + Assert.IsEmpty(loggerRunSettings.LoggerSettingsList); } [TestMethod] @@ -849,7 +850,7 @@ public void GetLoggerRunSettingsShouldReturnEmptyLoggersWhenLoggersIsSelfEnding( "; var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggersNode)!; - Assert.AreEqual(0, loggerRunSettings.LoggerSettingsList.Count); + Assert.IsEmpty(loggerRunSettings.LoggerSettingsList); } [TestMethod] @@ -878,11 +879,11 @@ public void GetLoggerRunSettingsShouldThrowWhenNodeOtherThanLoggerPresentInLogge exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains(string.Format( + Assert.Contains(string.Format( CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlElement, "Loggers", - "LoggerInvalid"))); + "LoggerInvalid"), exceptionMessage); } [TestMethod] @@ -912,7 +913,7 @@ public void GetLoggerRunSettingsShouldThrowWhenRequiredAttributesNotPresentInLog exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains(string.Format(CultureInfo.CurrentCulture, Resources.MissingLoggerAttributes, "LogGer"))); + Assert.Contains(string.Format(CultureInfo.CurrentCulture, Resources.MissingLoggerAttributes, "LogGer"), exceptionMessage); } [TestMethod] @@ -1051,7 +1052,7 @@ public void GetLoggerRunSettingsShouldReturnMultipleLoggersIfPresent() var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithMultipleLoggers)!; - Assert.AreEqual(3, loggerRunSettings.LoggerSettingsList.Count); + Assert.HasCount(3, loggerRunSettings.LoggerSettingsList); // 1st logger var loggerFirst = loggerRunSettings.LoggerSettingsList[0]; @@ -1102,7 +1103,7 @@ public void GetLoggerRunSettingsShouldReturnLoggersWhenLoggerHasSelfEndingTag() var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithSelfEndingLoggers)!; - Assert.AreEqual(3, loggerRunSettings.LoggerSettingsList.Count); + Assert.HasCount(3, loggerRunSettings.LoggerSettingsList); Assert.AreEqual("TestLoggerWithParameterExtension", loggerRunSettings.LoggerSettingsList[0].FriendlyName); Assert.AreEqual("TestLogger", loggerRunSettings.LoggerSettingsList[1].FriendlyName); Assert.AreEqual("TestLogger", loggerRunSettings.LoggerSettingsList[1].FriendlyName); @@ -1195,7 +1196,7 @@ public void GetDataCollectorsFriendlyNameShouldReturnListOfFriendlyName() var friendlyNameList = XmlRunSettingsUtilities.GetDataCollectorsFriendlyName(settingsXml).ToList(); - Assert.AreEqual(2, friendlyNameList.Count, "There should be two friendly name"); + Assert.HasCount(2, friendlyNameList); CollectionAssert.AreEqual(friendlyNameList, new List { "DummyDataCollector1", "DummyDataCollector2" }); } diff --git a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs index a36e70bb75..812875aac3 100644 --- a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs +++ b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs @@ -47,6 +47,8 @@ public class DefaultTestHostManagerTests private int _exitCode; private int _testHostId; + public TestContext TestContext { get; set; } = null!; + public DefaultTestHostManagerTests() { _mockProcessHelper = new Mock(); @@ -70,13 +72,13 @@ public void ConstructorShouldSetX86ProcessForX86Architecture() var info = _testHostManager.GetTestHostProcessStartInfo([], null, default); - StringAssert.EndsWith(info.FileName, "testhost.x86.exe"); + Assert.EndsWith("testhost.x86.exe", info.FileName); } [TestMethod] public void ConstructorShouldSetX64ProcessForX64Architecture() { - StringAssert.EndsWith(_startInfo.FileName, "testhost.exe"); + Assert.EndsWith("testhost.exe", _startInfo.FileName); } [TestMethod] @@ -86,7 +88,7 @@ public void GetTestHostProcessStartInfoShouldIncludeFileNameFromSubFolderTestHos _mockFileHelper.Setup(x => x.Exists(It.IsAny())).Returns(false); var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); - Assert.IsTrue(startInfo.FileName!.EndsWith(Path.Combine("TestHostNetFramework", "testhost.exe"))); + Assert.EndsWith(Path.Combine("TestHostNetFramework", "testhost.exe"), startInfo.FileName!); } [TestMethod] @@ -96,8 +98,8 @@ public void GetTestHostProcessStartInfoShouldNotIncludeFileNameFromSubFolderTest _mockFileHelper.Setup(x => x.Exists(It.IsAny())).Returns(true); var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); - Assert.IsFalse(startInfo.FileName!.EndsWith(Path.Combine("TestHost", "testhost.exe"))); - Assert.IsTrue(startInfo.FileName!.EndsWith("testhost.exe")); + Assert.DoesNotEndWith(Path.Combine("TestHost", "testhost.exe"), startInfo.FileName!); + Assert.EndsWith("testhost.exe", startInfo.FileName!); } [TestMethod] @@ -106,8 +108,8 @@ public void GetTestHostProcessStartInfoShouldNotIncludeFileNameFromSubFolderTest _mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("devenv.exe"); var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); - Assert.IsFalse(startInfo.FileName!.EndsWith(Path.Combine("TestHost", "testhost.exe"))); - Assert.IsTrue(startInfo.FileName!.EndsWith("testhost.exe")); + Assert.DoesNotEndWith(Path.Combine("TestHost", "testhost.exe"), startInfo.FileName!); + Assert.EndsWith("testhost.exe", startInfo.FileName!); } [TestMethod] @@ -140,7 +142,7 @@ public void GetTestHostConnectionInfoShouldIncludeEndpointRoleAndChannelType() [TestMethod] public void GetTestHostProcessStartInfoShouldIncludeEmptyEnvironmentVariables() { - Assert.AreEqual(0, _startInfo.EnvironmentVariables!.Count); + Assert.IsEmpty(_startInfo.EnvironmentVariables!); } [TestMethod] @@ -188,7 +190,7 @@ public void GetTestHostProcessStartInfoShouldUseMonoAsHostOnNonWindowsIfNotStart default); Assert.AreEqual("/usr/bin/mono", info.FileName); - StringAssert.Contains(info.Arguments, Path.Combine("TestHostNetFramework", "testhost.exe")); + Assert.Contains(Path.Combine("TestHostNetFramework", "testhost.exe"), info.Arguments!); } [TestMethod] @@ -205,8 +207,8 @@ public void GetTestHostProcessStartInfoShouldNotUseMonoAsHostOnNonWindowsIfStart default); var testHostPath = Path.Combine("TestHostNetFramework", "testhost.exe"); - StringAssert.EndsWith(info.FileName, testHostPath); - Assert.IsFalse(info.Arguments!.Contains(testHostPath)); + Assert.EndsWith(testHostPath, info.FileName); + Assert.DoesNotContain(testHostPath, info.Arguments!); } [TestMethod] @@ -357,8 +359,8 @@ public void LaunchTestHostShouldReturnTestHostProcessId() _testHostManager.HostLaunched += TestHostManagerHostLaunched; - Task processId = _testHostManager.LaunchTestHostAsync(startInfo, CancellationToken.None); - processId.Wait(); + Task processId = _testHostManager.LaunchTestHostAsync(startInfo, TestContext.CancellationToken); + processId.Wait(TestContext.CancellationToken); Assert.IsTrue(processId.Result); @@ -385,13 +387,13 @@ public void LaunchTestHostAsyncShouldNotStartHostProcessIfCancellationTokenIsSet CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); - Assert.ThrowsExactly(() => _testableTestHostManager.LaunchTestHostAsync(GetDefaultStartInfo(), cancellationTokenSource.Token).Wait()); + Assert.ThrowsExactly(() => _testableTestHostManager.LaunchTestHostAsync(GetDefaultStartInfo(), cancellationTokenSource.Token).Wait(TestContext.CancellationToken)); } [TestMethod] public void PropertiesShouldReturnEmptyDictionary() { - Assert.AreEqual(0, _testHostManager.Properties.Count); + Assert.IsEmpty(_testHostManager.Properties); } [TestMethod] @@ -424,8 +426,8 @@ public void LaunchTestHostShouldUseCustomHostIfSet() _testHostManager.HostLaunched += TestHostManagerHostLaunched; - Task pid = _testHostManager.LaunchTestHostAsync(_startInfo, CancellationToken.None); - pid.Wait(); + Task pid = _testHostManager.LaunchTestHostAsync(_startInfo, TestContext.CancellationToken); + pid.Wait(TestContext.CancellationToken); mockCustomLauncher.Verify(mc => mc.LaunchTestHost(It.IsAny(), It.IsAny()), Times.Once); Assert.IsTrue(pid.Result); @@ -439,7 +441,7 @@ public void LaunchTestHostShouldSetExitCallbackInCaseCustomHost() _testHostManager.SetCustomLauncher(mockCustomLauncher.Object); var currentProcess = Process.GetCurrentProcess(); mockCustomLauncher.Setup(mc => mc.LaunchTestHost(It.IsAny(), It.IsAny())).Returns(currentProcess.Id); - _testHostManager.LaunchTestHostAsync(_startInfo, CancellationToken.None).Wait(); + _testHostManager.LaunchTestHostAsync(_startInfo, TestContext.CancellationToken).Wait(TestContext.CancellationToken); _mockProcessHelper.Verify(ph => ph.SetExitCallback(currentProcess.Id, It.IsAny>())); } diff --git a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs index f85666ae8f..df735db55f 100644 --- a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs +++ b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs @@ -54,6 +54,8 @@ public class DotnetTestHostManagerTests private readonly string _temp = Path.GetTempPath(); + public TestContext TestContext { get; set; } = null!; + public DotnetTestHostManagerTests() { _mockTestHostLauncher = new Mock(); @@ -101,9 +103,11 @@ public DotnetTestHostManagerTests() .Setup(th => th.LaunchTestHost(It.IsAny(), It.IsAny())) .Returns(pid); +#pragma warning disable MSTEST0049 // Use 'TestContext.CancellationToken' - Moq setup pattern _mockTestHostLauncher .Setup(th => th.LaunchTestHost(It.IsAny())) .Returns(pid); +#pragma warning restore MSTEST0049 _defaultTestProcessStartInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { defaultSourcePath }, null, _defaultConnectionInfo); } @@ -153,7 +157,7 @@ public void GetTestHostProcessStartInfoShouldInvokeDotnetExec() _mockFileHelper.Setup(ph => ph.Exists("testhost.dll")).Returns(true); var startInfo = GetDefaultStartInfo(); - StringAssert.StartsWith(startInfo.Arguments, "exec"); + Assert.StartsWith("exec", startInfo.Arguments); } [TestMethod] @@ -164,7 +168,7 @@ public void GetTestHostProcessStartInfoShouldAddRuntimeConfigJsonIfExists() var startInfo = GetDefaultStartInfo(); - StringAssert.Contains(startInfo.Arguments, "--runtimeconfig \"test.runtimeconfig.json\""); + Assert.Contains("--runtimeconfig \"test.runtimeconfig.json\"", startInfo.Arguments!); } [TestMethod] @@ -175,7 +179,7 @@ public void GetTestHostProcessStartInfoShouldNotAddRuntimeConfigJsonIfNotExists( var startInfo = GetDefaultStartInfo(); - Assert.IsFalse(startInfo.Arguments!.Contains("--runtimeconfig \"test.runtimeconfig.json\"")); + Assert.DoesNotContain("--runtimeconfig \"test.runtimeconfig.json\"", startInfo.Arguments!); } [TestMethod] @@ -186,7 +190,7 @@ public void GetTestHostProcessStartInfoShouldAddDepsFileJsonIfExists() var startInfo = GetDefaultStartInfo(); - StringAssert.Contains(startInfo.Arguments, "--depsfile \"test.deps.json\""); + Assert.Contains("--depsfile \"test.deps.json\"", startInfo.Arguments!); } [TestMethod] @@ -197,7 +201,7 @@ public void GetTestHostProcessStartInfoShouldNotAddDepsFileJsonIfNotExists() var startInfo = GetDefaultStartInfo(); - Assert.IsFalse(startInfo.Arguments!.Contains("--depsfile \"test.deps.json\"")); + Assert.DoesNotContain("--depsfile \"test.deps.json\"", startInfo.Arguments!); } [TestMethod] @@ -208,7 +212,7 @@ public void GetTestHostProcessStartInfoShouldIncludeConnectionInfo() var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(_testSource, null, connectionInfo); - StringAssert.Contains(startInfo.Arguments, "--port " + connectionInfo.Port + " --endpoint " + connectionInfo.ConnectionInfo.Endpoint + " --role client --parentprocessid 101"); + Assert.Contains("--port " + connectionInfo.Port + " --endpoint " + connectionInfo.ConnectionInfo.Endpoint + " --role client --parentprocessid 101", startInfo.Arguments!); } [TestMethod] @@ -239,7 +243,7 @@ public void GetTestHostProcessStartIfDepsFileNotFoundAndTestHostFoundShouldNotTh _mockFileHelper.Setup(ph => ph.Exists("testhost.dll")).Returns(true); var startInfo = GetDefaultStartInfo(); - StringAssert.Contains(startInfo.Arguments, "testhost.dll"); + Assert.Contains("testhost.dll", startInfo.Arguments!); } [TestMethod] @@ -252,7 +256,7 @@ public void GetTestHostProcessStartInfoShouldUseTestHostX64ExePresentOnWindows() var startInfo = GetDefaultStartInfo(); - StringAssert.Contains(startInfo.FileName, testhostExePath); + Assert.Contains(testhostExePath, startInfo.FileName!); } [TestMethod] @@ -264,8 +268,8 @@ public void GetTestHostProcessStartInfoShouldUseDotnetExeOnUnixWithTestHostDllPa var startInfo = GetDefaultStartInfo(); - StringAssert.Contains(startInfo.FileName, "dotnet"); - StringAssert.Contains(startInfo.Arguments, "testhost.dll"); + Assert.Contains("dotnet", startInfo.FileName!); + Assert.Contains("testhost.dll", startInfo.Arguments!); } [TestMethod] @@ -279,7 +283,7 @@ public void GetTestHostProcessStartInfoShouldUseTestHostExeIfPresentOnWindows() _dotnetHostManager.Initialize(_mockMessageLogger.Object, "x64"); var startInfo = GetDefaultStartInfo(); - StringAssert.Contains(startInfo.FileName, testhostExePath); + Assert.Contains(testhostExePath, startInfo.FileName!); } [TestMethod] @@ -291,7 +295,7 @@ public void GetTestHostProcessStartInfoShouldUseDotnetHostPathFromRunsettings() _dotnetHostManager.Initialize(_mockMessageLogger.Object, $"{dotnetHostPath}"); var startInfo = GetDefaultStartInfo(); - StringAssert.Contains(startInfo.FileName, dotnetHostPath); + Assert.Contains(dotnetHostPath, startInfo.FileName!); } [TestMethod] @@ -364,7 +368,7 @@ public void GetTestHostProcessStartInfoShouldUseTestHostExeFromNugetIfNotFoundIn // If this starts failing after updating TFMs of packakges, the GetTestHostProcessStartInfo defines the default version // to use in GetTestHostProcessStartInfo, change that to the lowest supported netcore version, and pass this test. - StringAssert.Contains(startInfo.FileName, "C:\\packages\\microsoft.testplatform.testhost\\15.0.0-Dev\\build\\net8.0\\x64\\testhost.exe"); + Assert.Contains("C:\\packages\\microsoft.testplatform.testhost\\15.0.0-Dev\\build\\net8.0\\x64\\testhost.exe", startInfo.FileName!); } [TestMethod] @@ -436,7 +440,7 @@ public void GetTestHostProcessStartInfoShouldUseTestHostX86ExeFromNugetIfNotFoun // If this starts failing after updating TFMs of packakges, the GetTestHostProcessStartInfo defines the default version // to use in GetTestHostProcessStartInfo, change that to the lowest supported netcore version, and pass this test. - StringAssert.Contains(startInfo.FileName, "C:\\packages\\microsoft.testplatform.testhost\\15.0.0-Dev\\build\\net8.0\\x86\\testhost.x86.exe"); + Assert.Contains("C:\\packages\\microsoft.testplatform.testhost\\15.0.0-Dev\\build\\net8.0\\x86\\testhost.x86.exe", startInfo.FileName!); } [TestMethod] @@ -456,8 +460,8 @@ public void LaunchTestHostShouldLaunchProcessWithNullEnvironmentVariablesOrArgs( _dotnetHostManager.HostLaunched += DotnetHostManagerHostLaunched; - Task processId = _dotnetHostManager.LaunchTestHostAsync(startInfo, CancellationToken.None); - processId.Wait(); + Task processId = _dotnetHostManager.LaunchTestHostAsync(startInfo, TestContext.CancellationToken); + processId.Wait(TestContext.CancellationToken); Assert.IsTrue(processId.Result); Assert.AreEqual(expectedProcessId, _testHostId); @@ -473,14 +477,16 @@ public void LaunchTestHostAsyncShouldNotStartHostProcessIfCancellationTokenIsSet using (var p = Process.GetCurrentProcess()) expectedProcessId = p.Id; #endif +#pragma warning disable MSTEST0049 // Use 'TestContext.CancellationToken' - Moq setup pattern _mockTestHostLauncher.Setup(thl => thl.LaunchTestHost(It.IsAny())).Returns(expectedProcessId); +#pragma warning restore MSTEST0049 _mockFileHelper.Setup(ph => ph.Exists("testhost.dll")).Returns(true); var startInfo = GetDefaultStartInfo(); CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); - Assert.ThrowsExactly(() => _dotnetHostManager.LaunchTestHostAsync(startInfo, cancellationTokenSource.Token).Wait()); + Assert.ThrowsExactly(() => _dotnetHostManager.LaunchTestHostAsync(startInfo, cancellationTokenSource.Token).Wait(TestContext.CancellationToken)); } [TestMethod] @@ -492,8 +498,8 @@ public void LaunchTestHostShouldLaunchProcessWithEnvironmentVariables() _dotnetHostManager.HostLaunched += DotnetHostManagerHostLaunched; - Task processId = _dotnetHostManager.LaunchTestHostAsync(startInfo, CancellationToken.None); - processId.Wait(); + Task processId = _dotnetHostManager.LaunchTestHostAsync(startInfo, TestContext.CancellationToken); + processId.Wait(TestContext.CancellationToken); Assert.IsTrue(processId.Result); _mockTestHostLauncher.Verify(thl => thl.LaunchTestHost(It.Is(x => x.EnvironmentVariables!.Equals(variables)), It.IsAny()), Times.Once); @@ -597,7 +603,7 @@ public async Task LaunchTestHostShouldLaunchProcessWithConnectionInfo() #endif + " --port 123 --endpoint 127.0.0.1:123 --role client --parentprocessid 0"; _dotnetHostManager.SetCustomLauncher(_mockTestHostLauncher.Object); - await _dotnetHostManager.LaunchTestHostAsync(_defaultTestProcessStartInfo, CancellationToken.None); + await _dotnetHostManager.LaunchTestHostAsync(_defaultTestProcessStartInfo, TestContext.CancellationToken); _mockTestHostLauncher.Verify(thl => thl.LaunchTestHost(It.Is(x => x.Arguments!.Equals(expectedArgs)), It.IsAny()), Times.Once); } @@ -617,7 +623,7 @@ public void LaunchTestHostShouldSetExitCallBackInCaseCustomHost() var startInfo = GetDefaultStartInfo(); _dotnetHostManager.SetCustomLauncher(_mockTestHostLauncher.Object); - _dotnetHostManager.LaunchTestHostAsync(startInfo, CancellationToken.None).Wait(); + _dotnetHostManager.LaunchTestHostAsync(startInfo, TestContext.CancellationToken).Wait(TestContext.CancellationToken); _mockProcessHelper.Verify(ph => ph.SetExitCallback(expectedProcessId, It.IsAny>())); } @@ -633,7 +639,7 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathFromSourceDirect var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - StringAssert.Contains(startInfo.Arguments, expectedTestHostPath); + Assert.Contains(expectedTestHostPath, startInfo.Arguments!); } // TODO: This assembly was previously compiled as net472 and so it was skipped and only ran as net8.0. This fails in test, but works in code that is not isolated in appdomain. Might be worth fixing because we get one null here, and another in DotnetTestHostManager. @@ -653,13 +659,13 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathNextToTestRunner var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - StringAssert.Contains(startInfo.Arguments, expectedTestHostPath); + Assert.Contains(expectedTestHostPath, startInfo.Arguments!); var expectedAdditionalDepsPath = Path.Combine(here, "testhost.deps.json"); - StringAssert.Contains(startInfo.Arguments, $"--additional-deps \"{expectedAdditionalDepsPath}\""); + Assert.Contains($"--additional-deps \"{expectedAdditionalDepsPath}\"", startInfo.Arguments!); var expectedAdditionalProbingPath = here; - StringAssert.Contains(startInfo.Arguments, $"--additionalprobingpath \"{expectedAdditionalProbingPath}\""); + Assert.Contains($"--additionalprobingpath \"{expectedAdditionalProbingPath}\"", startInfo.Arguments!); var expectedRuntimeConfigPath = Path.Combine(here, "testhost-latest.runtimeconfig.json"); - StringAssert.Contains(startInfo.Arguments, $"--runtimeconfig \"{expectedRuntimeConfigPath}\""); + Assert.Contains($"--runtimeconfig \"{expectedRuntimeConfigPath}\"", startInfo.Arguments!); } #endif @@ -697,7 +703,7 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathNextToTestRunner var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); var expectedRuntimeConfigPath = Path.Combine(here, $"testhost-{suffix}.runtimeconfig.json"); - StringAssert.Contains(startInfo.Arguments, $"--runtimeconfig \"{expectedRuntimeConfigPath}\""); + Assert.Contains($"--runtimeconfig \"{expectedRuntimeConfigPath}\"", startInfo.Arguments!); } #endif @@ -713,7 +719,7 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathFromSourceDirect var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - Assert.IsTrue(startInfo.Arguments!.Contains(expectedTestHostPath)); + Assert.Contains(expectedTestHostPath, startInfo.Arguments!); } [TestMethod] @@ -778,7 +784,7 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathFromDepsFile() var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - Assert.IsTrue(startInfo.Arguments!.Contains(testHostFullPath)); + Assert.Contains(testHostFullPath, startInfo.Arguments!); } [TestMethod] @@ -845,7 +851,7 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathFromSourceDirect var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - Assert.IsTrue(startInfo.Arguments!.Contains(testHostPath)); + Assert.Contains(testHostPath, startInfo.Arguments!); } [TestMethod] @@ -911,7 +917,7 @@ public void GetTestHostProcessStartInfoShouldSkipInvalidAdditionalProbingPaths() var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - Assert.IsTrue(startInfo.Arguments!.Contains(testHostFullPath)); + Assert.Contains(testHostFullPath, startInfo.Arguments!); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.TestUtilities/CodeCoverageAcceptanceTestBase.cs b/test/Microsoft.TestPlatform.TestUtilities/CodeCoverageAcceptanceTestBase.cs index 9c648c4e1f..4137b7434c 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/CodeCoverageAcceptanceTestBase.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/CodeCoverageAcceptanceTestBase.cs @@ -52,7 +52,7 @@ protected static void AssertCoverage(ModuleData module, double expectedCoverage) string coverageData = module.CoverageBuffer.Length == 0 ? module.LineCoverage : module.BlockCoverage; var coverage = double.Parse(coverageData, CultureInfo.InvariantCulture); Console.WriteLine($"Checking coverage for {module.Name}. Expected at least: {expectedCoverage}. Result: {coverage}"); - Assert.IsTrue(coverage > expectedCoverage, $"Coverage check failed for {module.Name}. Expected at least: {expectedCoverage}. Found: {coverage}"); + Assert.IsGreaterThan(expectedCoverage, coverage, $"Coverage check failed for {module.Name}. Expected at least: {expectedCoverage}. Found: {coverage}"); } protected static string GetCoverageFileNameFromTrx(string trxFilePath, string resultsDirectory) @@ -62,10 +62,10 @@ protected static string GetCoverageFileNameFromTrx(string trxFilePath, string re using var trxStream = new FileStream(trxFilePath, FileMode.Open, FileAccess.Read); doc.Load(trxStream); var deploymentElements = doc.GetElementsByTagName("Deployment"); - Assert.IsTrue(deploymentElements.Count == 1, + Assert.HasCount(1, deploymentElements, "None or more than one Deployment tags found in trx file:{0}", trxFilePath); var deploymentDir = deploymentElements[0]!.Attributes!.GetNamedItem("runDeploymentRoot")?.Value; - Assert.IsTrue(StringUtils.IsNullOrEmpty(deploymentDir) == false, + Assert.IsFalse(StringUtils.IsNullOrEmpty(deploymentDir), "runDeploymentRoot attribute not found in trx file:{0}", trxFilePath); var collectors = doc.GetElementsByTagName("Collector"); @@ -80,7 +80,7 @@ protected static string GetCoverageFileNameFromTrx(string trxFilePath, string re } } - Assert.IsTrue(StringUtils.IsNullOrEmpty(fileName) == false, "Coverage file name not found in trx file: {0}", + Assert.IsFalse(StringUtils.IsNullOrEmpty(fileName), "Coverage file name not found in trx file: {0}", trxFilePath); return Path.Combine(resultsDirectory, deploymentDir, "In", fileName); } diff --git a/test/Microsoft.TestPlatform.TestUtilities/FileAssert.cs b/test/Microsoft.TestPlatform.TestUtilities/FileAssert.cs index 64b7c02938..d5cc8de32f 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/FileAssert.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/FileAssert.cs @@ -17,7 +17,7 @@ public static void Contains(string filePath, params string[] substrs) var fileContent = File.ReadAllText(filePath); foreach (var substr in substrs) { - Assert.IsTrue(fileContent.Contains(substr), + Assert.Contains(substr, fileContent, $"{filePath}: file doesn't contains {StringHighlighter} {substr} {StringHighlighter}"); } } diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs index d03ee27538..14ff918cc2 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs @@ -86,7 +86,7 @@ public void IntegrationTestBaseSetup() public TempDirectory TempDirectory { get; } - public TestContext? TestContext { get; set; } + public TestContext TestContext { get; set; } = null!; public string BuildConfiguration { get; } @@ -388,9 +388,9 @@ public void ValidateSummaryStatus(int passed, int failed, int skipped) _standardTestError, Environment.NewLine, _arguments); - StringAssert.DoesNotMatch( - _standardTestOutput, - new Regex(summaryStatus), errorSummary) + Assert.DoesNotMatchRegex( + new Regex(summaryStatus), + _standardTestOutput, errorSummary) ; } else @@ -417,8 +417,9 @@ public void ValidateSummaryStatus(int passed, int failed, int skipped) _standardTestError, Environment.NewLine, _arguments); - Assert.IsTrue( - _standardTestOutput.Contains(summaryStatus), + Assert.Contains( + summaryStatus, + _standardTestOutput, errorSummary ); } @@ -442,9 +443,9 @@ public void ValidateSummaryStatusv15(int passed, int failed, int skipped) _standardTestError, Environment.NewLine, _arguments); - StringAssert.DoesNotMatch( - _standardTestOutput, + Assert.DoesNotMatchRegex( new Regex("Total tests\\:"), + _standardTestOutput, errorSummary); } else @@ -471,15 +472,16 @@ public void ValidateSummaryStatusv15(int passed, int failed, int skipped) _standardTestError, Environment.NewLine, _arguments); - Assert.IsTrue( - _standardTestOutput.Contains(summaryStatus), + Assert.Contains( + summaryStatus, + _standardTestOutput, errorSummary); } } public void StdErrorContains(string substring) { - Assert.IsTrue(_standardTestError.Contains(substring), $"StdErrorOutput - [{_standardTestError}] did not contain expected string '{substring}'"); + Assert.Contains(substring, _standardTestError, $"StdErrorOutput - [{_standardTestError}] did not contain expected string '{substring}'"); } public void StdErrorRegexIsMatch(string pattern) @@ -489,17 +491,17 @@ public void StdErrorRegexIsMatch(string pattern) public void StdErrorDoesNotContains(string substring) { - Assert.IsFalse(_standardTestError.Contains(substring), $"StdErrorOutput - [{_standardTestError}] did not contain expected string '{substring}'"); + Assert.DoesNotContain(substring, _standardTestError, $"StdErrorOutput - [{_standardTestError}] did not contain expected string '{substring}'"); } public void StdOutputContains(string substring) { - Assert.IsTrue(_standardTestOutput.Contains(substring), $"{Environment.NewLine}StdOutput:{Environment.NewLine}{Environment.NewLine}Expected substring: {substring}{Environment.NewLine}{Environment.NewLine}Actual string: {_standardTestOutput}"); + Assert.Contains(substring, _standardTestOutput, $"{Environment.NewLine}StdOutput:{Environment.NewLine}{Environment.NewLine}Expected substring: {substring}{Environment.NewLine}{Environment.NewLine}Actual string: {_standardTestOutput}"); } public void StdOutputDoesNotContains(string substring) { - Assert.IsFalse(_standardTestOutput.Contains(substring), $"{Environment.NewLine}StdOutput:{Environment.NewLine}{Environment.NewLine}Not expected substring: {substring}{Environment.NewLine}{Environment.NewLine}Actual string: {_standardTestOutput}"); + Assert.DoesNotContain(substring, _standardTestOutput, $"{Environment.NewLine}StdOutput:{Environment.NewLine}{Environment.NewLine}Not expected substring: {substring}{Environment.NewLine}{Environment.NewLine}Actual string: {_standardTestOutput}"); } public void ExitCodeEquals(int exitCode) @@ -545,7 +547,7 @@ public void ValidateFailedTests(params string[] failedTests) Assert.IsTrue(flag, "Test {0} does not appear in failed tests list.", test); // Verify stack information as well. - Assert.IsTrue(_standardTestOutput.Contains(GetTestMethodName(test)), "No stack trace for failed test: {0}", test); + Assert.Contains(GetTestMethodName(test), _standardTestOutput, $"No stack trace for failed test: {test}"); } } @@ -599,7 +601,7 @@ public void ValidateTestsNotDiscovered(params string[] testsList) public void ValidateFullyQualifiedDiscoveredTests(string filePath, params string[] discoveredTestsList) { var fileOutput = File.ReadAllLines(filePath); - Assert.IsTrue(fileOutput.Length == 3); + Assert.HasCount(3, fileOutput); foreach (var test in discoveredTestsList) { diff --git a/test/Microsoft.TestPlatform.TestUtilities/SourceAssert.cs b/test/Microsoft.TestPlatform.TestUtilities/SourceAssert.cs index 85ba1e44a4..f5ca5e6cbe 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/SourceAssert.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/SourceAssert.cs @@ -28,10 +28,10 @@ public static void LineIsAtMethodBodyStart(string sourceFilePath, string methodN { var lines = File.ReadAllLines(sourceFilePath); var bodyStarts = SourceNavigationParser.FindMethodBodyStartLines(lines, methodName); - Assert.IsTrue(bodyStarts.Count > 0, $"Method '{methodName}' not found in '{sourceFilePath}'."); + Assert.IsNotEmpty(bodyStarts, $"Method '{methodName}' not found in '{sourceFilePath}'."); - Assert.IsTrue( - bodyStarts.Any(bodyStart => actualLineNumber == bodyStart || actualLineNumber == bodyStart + 1), + Assert.Contains( + bodyStart => actualLineNumber == bodyStart || actualLineNumber == bodyStart + 1, bodyStarts, message ?? $"Line {actualLineNumber} is not at the body start of method '{methodName}' in '{Path.GetFileName(sourceFilePath)}'." + $" Expected one of: {string.Join(", ", bodyStarts.SelectMany(b => new[] { b, b + 1 }).Distinct().OrderBy(x => x))}"); } @@ -46,12 +46,12 @@ public static void LineIsWithinMethod(string sourceFilePath, string methodName, { var lines = File.ReadAllLines(sourceFilePath); var locations = SourceNavigationParser.FindMethodLocations(lines, methodName); - Assert.IsTrue(locations.Count > 0, $"Method '{methodName}' not found in '{sourceFilePath}'."); + Assert.IsNotEmpty(locations, $"Method '{methodName}' not found in '{sourceFilePath}'."); // Allow from a few lines before the signature (to cover attributes like [TestMethod]) through body start + 1. const int attributeMargin = 5; - Assert.IsTrue( - locations.Any(loc => actualLineNumber >= loc.SignatureLine - attributeMargin && actualLineNumber <= loc.BodyStartLine + 1), + Assert.Contains( + loc => actualLineNumber >= loc.SignatureLine - attributeMargin && actualLineNumber <= loc.BodyStartLine + 1, locations, message ?? $"Line {actualLineNumber} is not within any overload of method '{methodName}' in '{Path.GetFileName(sourceFilePath)}'." + $" Method ranges: {string.Join(", ", locations.Select(loc => $"[{loc.SignatureLine - attributeMargin}-{loc.BodyStartLine + 1}]"))}"); } diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs index 8303645db8..05f7ba5e5e 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs @@ -78,12 +78,12 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnEmptySetWhenNoAt _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); Assert.IsNotNull(resultAttachmentSets); - Assert.IsTrue(resultAttachmentSets.Count == 0); + Assert.IsEmpty(resultAttachmentSets); resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, null, _mockProgressReporter.Object, null, CancellationToken.None); Assert.IsNotNull(resultAttachmentSets); - Assert.IsTrue(resultAttachmentSets.Count == 0); + Assert.IsEmpty(resultAttachmentSets); _mockProgressReporter.Verify(p => p.Report(It.IsAny()), Times.Never); } @@ -99,8 +99,8 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnly1Atta _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); Assert.IsNotNull(resultAttachmentSets); - Assert.IsTrue(resultAttachmentSets.Count == 1); - Assert.IsTrue(resultAttachmentSets.First().Attachments.Count == 1); + Assert.HasCount(1, resultAttachmentSets); + Assert.HasCount(1, resultAttachmentSets.First().Attachments); Assert.AreEqual("datacollector://microsoft/CodeCoverage/2.0", resultAttachmentSets.First().Uri.AbsoluteUri); Assert.AreEqual("file:///C:/temp/aa.coverage", resultAttachmentSets.First().Attachments.First().Uri.AbsoluteUri); } @@ -119,8 +119,8 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIf2Differen _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); Assert.IsNotNull(resultAttachmentSets); - Assert.IsTrue(resultAttachmentSets.Count == 1); - Assert.IsTrue(resultAttachmentSets.First().Attachments.Count == 2); + Assert.HasCount(1, resultAttachmentSets); + Assert.HasCount(2, resultAttachmentSets.First().Attachments); Assert.AreEqual("datacollector://microsoft/CodeCoverage/2.0", resultAttachmentSets.First().Uri.AbsoluteUri); Assert.AreEqual("datacollector://microsoft/CodeCoverage/2.0", resultAttachmentSets.Last().Uri.AbsoluteUri); Assert.AreEqual(_filePrefix + file1Path.Replace("\\", "/").Replace(" ", "%20"), resultAttachmentSets.First().Attachments.First().Uri.AbsoluteUri); @@ -140,8 +140,8 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIf2SameForm _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); Assert.IsNotNull(resultAttachmentSets); - Assert.IsTrue(resultAttachmentSets.Count == 1); - Assert.IsTrue(resultAttachmentSets.First().Attachments.Count == 1); + Assert.HasCount(1, resultAttachmentSets); + Assert.HasCount(1, resultAttachmentSets.First().Attachments); Assert.AreEqual("datacollector://microsoft/CodeCoverage/2.0", resultAttachmentSets.First().Uri.AbsoluteUri); Assert.AreEqual(_filePrefix + file1Path.Replace("\\", "/").Replace(" ", "%20"), resultAttachmentSets.First().Attachments.First().Uri.AbsoluteUri); } @@ -157,8 +157,8 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnly1Logs _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); Assert.IsNotNull(resultAttachmentSets); - Assert.IsTrue(resultAttachmentSets.Count == 1); - Assert.IsTrue(resultAttachmentSets.First().Attachments.Count == 1); + Assert.HasCount(1, resultAttachmentSets); + Assert.HasCount(1, resultAttachmentSets.First().Attachments); Assert.AreEqual("datacollector://microsoft/CodeCoverage/2.0", resultAttachmentSets.First().Uri.AbsoluteUri); Assert.AreEqual("file:///C:/temp/aa.logs", resultAttachmentSets.First().Attachments.First().Uri.AbsoluteUri); } @@ -178,9 +178,9 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnlySever _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); Assert.IsNotNull(resultAttachmentSets); - Assert.IsTrue(resultAttachmentSets.Count == 2); - Assert.IsTrue(resultAttachmentSets.First().Attachments.Count == 1); - Assert.IsTrue(resultAttachmentSets.Last().Attachments.Count == 2); + Assert.HasCount(2, resultAttachmentSets); + Assert.HasCount(1, resultAttachmentSets.First().Attachments); + Assert.HasCount(2, resultAttachmentSets.Last().Attachments); } [TestMethod] @@ -199,7 +199,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldThrowIfCancellationReq await Assert.ThrowsExactlyAsync(async () => await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, cts.Token)); - Assert.AreEqual(2, attachment.Count); + Assert.HasCount(2, attachment); _mockProgressReporter.Verify(p => p.Report(It.IsAny()), Times.Never); } @@ -220,8 +220,8 @@ public async Task MergingPerTestCodeCoverageReturnsOneCoverageFile() _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(doc.DocumentElement!, attachment, _mockProgressReporter.Object, _messageLogger.Object, CancellationToken.None); Assert.IsNotNull(resultAttachmentSets); - Assert.IsTrue(resultAttachmentSets.Count == 1); - Assert.IsTrue(resultAttachmentSets.First().Attachments.Count == 1); + Assert.HasCount(1, resultAttachmentSets); + Assert.HasCount(1, resultAttachmentSets.First().Attachments); Assert.AreEqual("datacollector://microsoft/CodeCoverage/2.0", resultAttachmentSets.First().Uri.AbsoluteUri); } } diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageRunSettingsProcessorTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageRunSettingsProcessorTests.cs index e6023e99b7..a678cb6267 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageRunSettingsProcessorTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageRunSettingsProcessorTests.cs @@ -250,7 +250,7 @@ private static void CompareResults(XmlNode currentSettingsRoot, XmlNode defaultS { var nodes = ExtractNodes(currentSettingsRoot, defaultSettingsRoot, path); - Assert.AreEqual(nodes.Item1.ChildNodes.Count, nodes.Item2.ChildNodes.Count); + Assert.HasCount(nodes.Item1.ChildNodes.Count, nodes.Item2.ChildNodes); var set = new HashSet(); foreach (XmlNode child in nodes.Item1.ChildNodes) @@ -272,7 +272,7 @@ private static void CompareResults(XmlNode currentSettingsRoot, XmlNode defaultS set.Remove(child.OuterXml); } - Assert.AreEqual(0, set.Count); + Assert.IsEmpty(set); } #endregion } diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs index 8fd82db468..4e6276e557 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs @@ -78,7 +78,7 @@ public void UpdateRunSettingsShouldUpdateWithPlatformSettings() var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, "X86"); + Assert.Contains("X86", xml); } [TestMethod] @@ -91,7 +91,7 @@ public void UpdateRunSettingsShouldUpdateWithFrameworkSettings() var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, $"{Framework.DefaultFramework.Name}"); + Assert.Contains($"{Framework.DefaultFramework.Name}", xml); } [TestMethod] @@ -104,7 +104,7 @@ public void UpdateRunSettingsShouldUpdateWithResultsDirectorySettings() var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, "temp"); + Assert.Contains("temp", xml); } [TestMethod] @@ -117,7 +117,7 @@ public void UpdateRunSettingsShouldNotUpdatePlatformIfRunSettingsAlreadyHasIt() var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, "X86"); + Assert.Contains("X86", xml); } [TestMethod] @@ -130,7 +130,7 @@ public void UpdateRunSettingsShouldNotUpdateFrameworkIfRunSettingsAlreadyHasIt() var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, ".NETFramework,Version=v4.0"); + Assert.Contains(".NETFramework,Version=v4.0", xml); } //TargetFrameworkMoniker @@ -145,7 +145,7 @@ public void UpdateRunSettingsShouldAllowTargetFrameworkMonikerValue() var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, ".NETFramework,Version=v4.0"); + Assert.Contains(".NETFramework,Version=v4.0", xml); } [TestMethod] @@ -158,7 +158,7 @@ public void UpdateRunSettingsShouldNotUpdateResultsDirectoryIfRunSettingsAlready var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, "someplace"); + Assert.Contains("someplace", xml); } [TestMethod] @@ -171,9 +171,9 @@ public void UpdateRunSettingsShouldNotUpdatePlatformOrFrameworkOrResultsDirector var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, "X86"); - StringAssert.Contains(xml, "Framework40"); - StringAssert.Contains(xml, "someplace"); + Assert.Contains("X86", xml); + Assert.Contains("Framework40", xml); + Assert.Contains("someplace", xml); } [TestMethod] @@ -186,9 +186,9 @@ public void UpdateRunSettingsWithAnEmptyRunSettingsShouldAddValuesSpecifiedInRun var xml = xmlDocument.OuterXml; - StringAssert.Contains(xml, "X64"); - StringAssert.Contains(xml, $"{Framework.DefaultFramework.Name}"); - StringAssert.Contains(xml, "temp"); + Assert.Contains("X64", xml); + Assert.Contains($"{Framework.DefaultFramework.Name}", xml); + Assert.Contains("temp", xml); } [TestMethod] @@ -240,7 +240,7 @@ public void MakeRunsettingsCompatibleShouldDeleteNewlyAddedRunConfigurationNode( var result = InferRunSettingsHelper.MakeRunsettingsCompatible(settings)!; - Assert.IsTrue(result.IndexOf("DesignMode", StringComparison.OrdinalIgnoreCase) < 0); + Assert.IsLessThan(0, result.IndexOf("DesignMode", StringComparison.OrdinalIgnoreCase)); } [TestMethod] @@ -263,14 +263,14 @@ public void MakeRunsettingsCompatibleShouldNotDeleteOldRunConfigurationNode() var result = InferRunSettingsHelper.MakeRunsettingsCompatible(settings)!; - Assert.IsTrue(result.IndexOf("TargetPlatform", StringComparison.OrdinalIgnoreCase) > 0); - Assert.IsTrue(result.IndexOf("TargetFrameworkVersion", StringComparison.OrdinalIgnoreCase) > 0); - Assert.IsTrue(result.IndexOf("TestAdaptersPaths", StringComparison.OrdinalIgnoreCase) > 0); - Assert.IsTrue(result.IndexOf("ResultsDirectory", StringComparison.OrdinalIgnoreCase) > 0); - Assert.IsTrue(result.IndexOf("SolutionDirectory", StringComparison.OrdinalIgnoreCase) > 0); - Assert.IsTrue(result.IndexOf("MaxCpuCount", StringComparison.OrdinalIgnoreCase) > 0); - Assert.IsTrue(result.IndexOf("DisableParallelization", StringComparison.OrdinalIgnoreCase) > 0); - Assert.IsTrue(result.IndexOf("DisableAppDomain", StringComparison.OrdinalIgnoreCase) > 0); + Assert.IsGreaterThan(0, result.IndexOf("TargetPlatform", StringComparison.OrdinalIgnoreCase)); + Assert.IsGreaterThan(0, result.IndexOf("TargetFrameworkVersion", StringComparison.OrdinalIgnoreCase)); + Assert.IsGreaterThan(0, result.IndexOf("TestAdaptersPaths", StringComparison.OrdinalIgnoreCase)); + Assert.IsGreaterThan(0, result.IndexOf("ResultsDirectory", StringComparison.OrdinalIgnoreCase)); + Assert.IsGreaterThan(0, result.IndexOf("SolutionDirectory", StringComparison.OrdinalIgnoreCase)); + Assert.IsGreaterThan(0, result.IndexOf("MaxCpuCount", StringComparison.OrdinalIgnoreCase)); + Assert.IsGreaterThan(0, result.IndexOf("DisableParallelization", StringComparison.OrdinalIgnoreCase)); + Assert.IsGreaterThan(0, result.IndexOf("DisableAppDomain", StringComparison.OrdinalIgnoreCase)); } [TestMethod] @@ -490,7 +490,7 @@ public void TryGetLegacySettingsForRunSettingsWithEmptyLegacySettingsShouldRetur "; Assert.IsTrue(InferRunSettingsHelper.TryGetLegacySettingElements(runSettingsXml, out Dictionary legacySettings)); - Assert.AreEqual(0, legacySettings.Count); + Assert.IsEmpty(legacySettings); } [TestMethod] @@ -519,7 +519,7 @@ public void TryGetLegacySettingsForRunSettingsWithValidLegacySettingsShouldRetur var expectedExecutionAttributes = "hostProcessPlatform, parallelTestCount"; Assert.IsTrue(InferRunSettingsHelper.TryGetLegacySettingElements(runSettingsXml, out Dictionary legacySettings)); - Assert.AreEqual(3, legacySettings.Count, "count does not match"); + Assert.HasCount(3, legacySettings, "count does not match"); Assert.AreEqual(expectedElements, legacySettings["Elements"]); Assert.AreEqual(expectedDeploymentAttributes, legacySettings["DeploymentAttributes"]); Assert.AreEqual(expectedExecutionAttributes, legacySettings["ExecutionAttributes"]); @@ -539,7 +539,7 @@ public void GetEnvironmentVariablesWithValidValuesInRunSettingsShouldReturnValid var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettingsXml)!; - Assert.AreEqual(2, envVars.Count); + Assert.HasCount(2, envVars); Assert.AreEqual(@"C:\temp", envVars["RANDOM_PATH"]); Assert.AreEqual(@"C:\temp2", envVars["RANDOM_PATH2"]); } @@ -558,7 +558,7 @@ public void GetEnvironmentVariablesWithDuplicateEnvValuesInRunSettingsShouldRetu var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettingsXml)!; - Assert.AreEqual(1, envVars.Count); + Assert.HasCount(1, envVars); Assert.AreEqual(@"C:\temp", envVars["RANDOM_PATH"]); } @@ -573,7 +573,7 @@ public void GetEnvironmentVariablesWithEmptyVariablesInRunSettingsShouldReturnEm "; var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettingsXml)!; - Assert.AreEqual(0, envVars.Count); + Assert.IsEmpty(envVars); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/StringUtilitiesTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/StringUtilitiesTests.cs index 85bb55149b..d967672431 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/StringUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/StringUtilitiesTests.cs @@ -29,8 +29,8 @@ public void SplitShouldReturnWhenStringDoesntContainSplitChar() var argsList = data.Tokenize(SplitChar, EscapeChar); var enumerable = argsList as string[] ?? argsList.ToArray(); - Assert.IsTrue(enumerable.Length == 1); - Assert.IsTrue(enumerable.First().Equals(data)); + Assert.HasCount(1, enumerable); + Assert.AreEqual(data, enumerable.First()); } [TestMethod] @@ -40,7 +40,7 @@ public void SplitShouldSplitWhenStringContainsSplitChar() var argsList = data.Tokenize(SplitChar, EscapeChar); var enumerable = argsList as string[] ?? argsList.ToArray(); - Assert.IsTrue(enumerable.Length == 2); + Assert.HasCount(2, enumerable); } [TestMethod] @@ -50,7 +50,7 @@ public void SplitShouldSplitWhenStringWithSplitCharStartEnd() var argsList = data.Tokenize(SplitChar, EscapeChar); var enumerable = argsList as string[] ?? argsList.ToArray(); - Assert.IsTrue(enumerable.Length == 4); + Assert.HasCount(4, enumerable); } [TestMethod] @@ -60,8 +60,8 @@ public void SplitShouldEscapeSplitCharWhenEscapedCharPresent() var argsList = data.Tokenize(SplitChar, EscapeChar); var enumerable = argsList as string[] ?? argsList.ToArray(); - Assert.IsTrue(enumerable.Length == 1); - Assert.IsTrue(enumerable.First().Equals("foo,bar")); + Assert.HasCount(1, enumerable); + Assert.AreEqual("foo,bar", enumerable.First()); } [TestMethod] @@ -70,8 +70,8 @@ public void SplitShouldEscapeSplitCharWhenEscapedNonEscapedCharPresent() var data = "foo\\,,bar"; var argsList = data.Tokenize(SplitChar, EscapeChar); var enumerable = argsList as string[] ?? argsList.ToArray(); - Assert.IsTrue(enumerable.Length == 2); - Assert.IsTrue(enumerable.First().Equals("foo,")); + Assert.HasCount(2, enumerable); + Assert.AreEqual("foo,", enumerable.First()); } [TestMethod] @@ -81,7 +81,7 @@ public void SplitShouldSplitWhenOnlySplitCharPresent() var argsList = data.Tokenize(SplitChar, EscapeChar); var enumerable = argsList as string[] ?? argsList.ToArray(); - Assert.IsTrue(enumerable.Length == 2); + Assert.HasCount(2, enumerable); } [TestMethod] @@ -91,7 +91,7 @@ public void SplitShouldNotSplitWhenNoSplitCharPresent() var argsList = data.Tokenize(SplitChar, EscapeChar); var enumerable = argsList as string[] ?? argsList.ToArray(); - Assert.IsTrue(enumerable.Length == 1); + Assert.HasCount(1, enumerable); } private const char SplitChar = ','; diff --git a/test/SettingsMigrator.UnitTests/MigratorTests.cs b/test/SettingsMigrator.UnitTests/MigratorTests.cs index f0b9b437e5..bce464e8b4 100644 --- a/test/SettingsMigrator.UnitTests/MigratorTests.cs +++ b/test/SettingsMigrator.UnitTests/MigratorTests.cs @@ -93,7 +93,7 @@ public void MigratorGeneratesCorrectRunsettingsWithDc() Assert.IsNotNull(root); var dataCollectorNode = root.SelectNodes(@"/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); Assert.IsNotNull(dataCollectorNode); - Assert.AreEqual(2, dataCollectorNode.Count, "Data collector is missing"); + Assert.HasCount(2, dataCollectorNode, "Data collector is missing"); } [TestMethod] diff --git a/test/SettingsMigrator.UnitTests/PathResolverTests.cs b/test/SettingsMigrator.UnitTests/PathResolverTests.cs index 678865ddd4..82257bad9f 100644 --- a/test/SettingsMigrator.UnitTests/PathResolverTests.cs +++ b/test/SettingsMigrator.UnitTests/PathResolverTests.cs @@ -67,7 +67,7 @@ public void PathResolverShouldReturnRunsettingsPathOfSameLocationAsTestSettings( var newFilePath = _pathResolver.GetTargetPath(["C:\\asd.testsettings"]); Assert.IsNotNull(newFilePath, "File path should not be null."); Assert.IsTrue(string.Equals(Path.GetExtension(newFilePath), ".runsettings"), "File path should be .runsettings"); - Assert.IsTrue(newFilePath!.Contains("C:\\asd_"), "File should be of same name as testsettings"); + Assert.Contains("C:\\asd_", newFilePath!, "File should be of same name as testsettings"); var time = newFilePath.Substring(7, 19); Assert.IsTrue(DateTime.TryParseExact(time, "MM-dd-yyyy_hh-mm-ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out _), "File name should have datetime"); } diff --git a/test/TranslationLayer.UnitTests/ConsoleParametersTests.cs b/test/TranslationLayer.UnitTests/ConsoleParametersTests.cs index 2fb8e72515..c6fa2ba453 100644 --- a/test/TranslationLayer.UnitTests/ConsoleParametersTests.cs +++ b/test/TranslationLayer.UnitTests/ConsoleParametersTests.cs @@ -26,7 +26,7 @@ public void LogFilePathShouldEnsureDoubleQuote() string result = sut.LogFilePath; - Assert.IsTrue(result.StartsWith("\"")); + Assert.StartsWith("\"", result); } [TestMethod] diff --git a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs index 296488587f..06b4317610 100644 --- a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs +++ b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs @@ -23,6 +23,8 @@ using Moq; +#pragma warning disable MSTEST0049 // Use 'TestContext.CancellationToken' - suppressed for Moq setup patterns + using Newtonsoft.Json.Linq; using Payloads = Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Payloads; @@ -40,6 +42,8 @@ public class VsTestConsoleRequestSenderTests private readonly IDataSerializer _serializer = JsonDataSerializer.Instance; private readonly Mock _telemetryHandler; + public TestContext TestContext { get; set; } = null!; + public VsTestConsoleRequestSenderTests() { _mockCommunicationManager = new Mock(); @@ -82,7 +86,7 @@ public void InitializeCommunicationShouldReturnInvalidPortNumberIfHostServerFail _mockCommunicationManager.Setup(cm => cm.AcceptClientAsync()).Returns(Task.FromResult(false)); var portOutput = _requestSender.InitializeCommunication(); - Assert.IsTrue(portOutput < 0, "Negative port number must be returned if Hosting Server fails."); + Assert.IsLessThan(0, portOutput, "Negative port number must be returned if Hosting Server fails."); var connectionSuccess = _requestSender.WaitForRequestHandlerConnection(_waitTimeout); Assert.IsFalse(connectionSuccess, "Connection must fail as server failed to host."); @@ -100,7 +104,7 @@ public async Task InitializeCommunicationAsyncShouldReturnInvalidPortNumberIfHos _mockCommunicationManager.Setup(cm => cm.AcceptClientAsync()).Returns(Task.FromResult(false)); var portOutput = await _requestSender.InitializeCommunicationAsync(_waitTimeout); - Assert.IsTrue(portOutput < 0, "Negative port number must be returned if Hosting Server fails."); + Assert.IsLessThan(0, portOutput, "Negative port number must be returned if Hosting Server fails."); _mockCommunicationManager.Verify(cm => cm.HostServer(new IPEndPoint(IPAddress.Loopback, 0)), Times.Once); _mockCommunicationManager.Verify(cm => cm.AcceptClientAsync(), Times.Never); @@ -114,7 +118,7 @@ public void InitializeCommunicationShouldFailConnectionIfMessageReceiveFailed() _mockCommunicationManager.Setup(cm => cm.HostServer(new IPEndPoint(IPAddress.Loopback, 0))).Returns(new IPEndPoint(IPAddress.Loopback, dummyPortInput)); _mockCommunicationManager.Setup(cm => cm.AcceptClientAsync()).Returns(Task.FromResult(false)).Callback(() => { }); _mockCommunicationManager.Setup(cm => cm.WaitForClientConnection(Timeout.Infinite)) - .Callback((int timeout) => Task.Delay(200).Wait()); + .Callback((int timeout) => Task.Delay(200, TestContext.CancellationToken).Wait()); _mockCommunicationManager.Setup(cm => cm.ReceiveMessage()).Throws(new Exception("Fail")); var portOutput = _requestSender.InitializeCommunication(); @@ -153,7 +157,7 @@ public void InitializeCommunicationShouldFailConnectionIfSessionConnectedDidNotC _mockCommunicationManager.Setup(cm => cm.HostServer(new IPEndPoint(IPAddress.Loopback, 0))).Returns(new IPEndPoint(IPAddress.Loopback, dummyPortInput)); _mockCommunicationManager.Setup(cm => cm.AcceptClientAsync()).Returns(Task.FromResult(false)).Callback(() => { }); _mockCommunicationManager.Setup(cm => cm.WaitForClientConnection(Timeout.Infinite)) - .Callback((int timeout) => Task.Delay(200).Wait()); + .Callback((int timeout) => Task.Delay(200, TestContext.CancellationToken).Wait()); var discoveryMessage = new Message() { MessageType = MessageType.StartDiscovery }; @@ -201,7 +205,7 @@ public void InitializeCommunicationShouldFailConnectionIfSendMessageFailed() _mockCommunicationManager.Setup(cm => cm.HostServer(new IPEndPoint(IPAddress.Loopback, 0))).Returns(new IPEndPoint(IPAddress.Loopback, dummyPortInput)); _mockCommunicationManager.Setup(cm => cm.AcceptClientAsync()).Returns(Task.FromResult(false)).Callback(() => { }); _mockCommunicationManager.Setup(cm => cm.WaitForClientConnection(Timeout.Infinite)) - .Callback((int timeout) => Task.Delay(200).Wait()); + .Callback((int timeout) => Task.Delay(200, TestContext.CancellationToken).Wait()); var sessionConnected = new Message() { MessageType = MessageType.SessionConnected }; @@ -252,7 +256,7 @@ public void InitializeCommunicationShouldFailConnectionIfProtocolIsNotCompatible _mockCommunicationManager.Setup(cm => cm.AcceptClientAsync()).Returns(Task.FromResult(false)).Callback(() => { }); _mockCommunicationManager.Setup(cm => cm.WaitForClientConnection(Timeout.Infinite)) - .Callback((int timeout) => Task.Delay(200).Wait()); + .Callback((int timeout) => Task.Delay(200, TestContext.CancellationToken).Wait()); var sessionConnected = new Message() { MessageType = MessageType.SessionConnected }; @@ -465,7 +469,7 @@ public void DiscoverTestsShouldCompleteWithSingleFullyDiscoveredSource() mockHandler.Verify(mh => mh.HandleDiscoveryComplete(It.IsAny(), null), Times.Once, "Discovery Complete must be called"); Assert.IsNotNull(receivedDiscoveryCompleteEventArgs!.FullyDiscoveredSources); - Assert.AreEqual(1, receivedDiscoveryCompleteEventArgs.FullyDiscoveredSources.Count); + Assert.HasCount(1, receivedDiscoveryCompleteEventArgs.FullyDiscoveredSources); } [TestMethod] @@ -508,9 +512,9 @@ public void DiscoverTestsShouldCompleteWithCorrectAbortedValuesIfAbortingWasRequ // Assert mockHandler.Verify(mh => mh.HandleDiscoveryComplete(It.IsAny(), null), Times.Once, "Discovery Complete must be called"); Assert.IsNotNull(receivedDiscoveryCompleteEventArgs!.FullyDiscoveredSources); - Assert.AreEqual(1, receivedDiscoveryCompleteEventArgs.FullyDiscoveredSources.Count); + Assert.HasCount(1, receivedDiscoveryCompleteEventArgs.FullyDiscoveredSources); Assert.AreEqual(-1, receivedDiscoveryCompleteEventArgs.TotalCount); - Assert.AreEqual(true, receivedDiscoveryCompleteEventArgs.IsAborted); + Assert.IsTrue(receivedDiscoveryCompleteEventArgs.IsAborted); } [TestMethod] @@ -542,7 +546,7 @@ public void DiscoverTestsShouldReportBackTestsWithTraitsInTestsFoundMessage() _requestSender.DiscoverTests(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); Assert.IsNotNull(receivedTestCases); - Assert.AreEqual(1, receivedTestCases.Count); + Assert.HasCount(1, receivedTestCases); // Verify that the traits are passed through properly. var traits = receivedTestCases.ToArray()[0].Traits; @@ -580,7 +584,7 @@ public async Task DiscoverTestsAsyncShouldReportBackTestsWithTraitsInTestsFoundM await _requestSender.DiscoverTestsAsync(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); Assert.IsNotNull(receivedTestCases); - Assert.AreEqual(1, receivedTestCases.Count); + Assert.HasCount(1, receivedTestCases); // Verify that the traits are passed through properly. var traits = receivedTestCases.ToArray()[0].Traits; @@ -613,7 +617,7 @@ public void DiscoverTestsShouldReportBackTestsWithTraitsInDiscoveryCompleteMessa _requestSender.DiscoverTests(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); Assert.IsNotNull(receivedTestCases); - Assert.AreEqual(1, receivedTestCases.Count); + Assert.HasCount(1, receivedTestCases); // Verify that the traits are passed through properly. var traits = receivedTestCases.ToArray()[0].Traits; @@ -646,7 +650,7 @@ public async Task DiscoverTestsAsyncShouldReportBackTestsWithTraitsInDiscoveryCo await _requestSender.DiscoverTestsAsync(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); Assert.IsNotNull(receivedTestCases); - Assert.AreEqual(1, receivedTestCases.Count); + Assert.HasCount(1, receivedTestCases); // Verify that the traits are passed through properly. var traits = receivedTestCases.ToArray()[0].Traits; @@ -2822,7 +2826,7 @@ private void InitializeCommunication(int protocolVersion) _mockCommunicationManager.Setup(cm => cm.AcceptClientAsync()).Returns(Task.FromResult(false)).Callback(() => { }); _mockCommunicationManager.Setup(cm => cm.WaitForClientConnection(Timeout.Infinite)) - .Callback((int timeout) => Task.Delay(200).Wait()); + .Callback((int timeout) => Task.Delay(200, TestContext.CancellationToken).Wait()); var sessionConnected = new Message() { MessageType = MessageType.SessionConnected }; var versionCheck = new Message() { MessageType = MessageType.VersionCheck, Payload = protocolVersion }; @@ -2887,3 +2891,4 @@ private async Task InitializeCommunicationAsync(int protocolVersion) #endregion } +#pragma warning restore MSTEST0049 diff --git a/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs b/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs index 27b26d83c5..67a68cb78a 100644 --- a/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs +++ b/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs @@ -71,7 +71,7 @@ public void AfterTestRunShouldSendGetAttachments() Assert.AreEqual("CustomDataCollector", dataCollectionResult.Attachments![0].DisplayName); Assert.AreEqual("my://custom/datacollector", dataCollectionResult.Attachments[0].Uri.ToString()); - Assert.IsTrue(dataCollectionResult.Attachments[0].Attachments[0].Uri.ToString().Contains("filename.txt")); + Assert.Contains("filename.txt", dataCollectionResult.Attachments[0].Attachments[0].Uri.ToString()); } [TestMethod] diff --git a/test/datacollector.UnitTests/DataCollectionAttachmentManagerTests.cs b/test/datacollector.UnitTests/DataCollectionAttachmentManagerTests.cs index 37c3d6b287..eb84270bbf 100644 --- a/test/datacollector.UnitTests/DataCollectionAttachmentManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionAttachmentManagerTests.cs @@ -27,6 +27,8 @@ public class DataCollectionAttachmentManagerTests private readonly SessionId _sessionId; private static readonly string TempDirectoryPath = Path.GetTempPath(); + public TestContext TestContext { get; set; } + public DataCollectionAttachmentManagerTests() { _attachmentManager = new DataCollectionAttachmentManager(); @@ -69,10 +71,10 @@ public void ParallelAccessShouldNotBreak() } _ = TestCaseEvent($"test_{Guid.NewGuid()}"); } - })); + }, TestContext.CancellationToken)); } - Task.WaitAll(parallelTasks.ToArray()); + Task.WaitAll(parallelTasks.ToArray(), TestContext.CancellationToken); } finally { @@ -134,7 +136,7 @@ public void AddAttachmentShouldNotAddNewFileTransferIfSessionIsNotConfigured() _attachmentManager.AddAttachment(dataCollectorDataMessage, null, uri, friendlyName); - Assert.AreEqual(0, _attachmentManager.AttachmentSets.Count); + Assert.IsEmpty(_attachmentManager.AttachmentSets); } [TestMethod] @@ -162,7 +164,7 @@ public void AddAttachmentShouldAddNewFileTransferAndCopyFileToOutputDirectoryIfD Assert.IsTrue(File.Exists(Path.Combine(TempDirectoryPath, filename))); Assert.IsTrue(File.Exists(Path.Combine(TempDirectoryPath, _sessionId.Id.ToString(), filename))); - Assert.AreEqual(1, _attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count); + Assert.HasCount(1, _attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments); } [TestMethod] @@ -196,8 +198,8 @@ public void AddAttachmentsShouldAddFilesCorrespondingToDifferentDataCollectors() // Wait for file operations to complete waitHandle.WaitOne(Timeout); - Assert.AreEqual(1, _attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count); - Assert.AreEqual(1, _attachmentManager.AttachmentSets[datacollectioncontext][uri1].Attachments.Count); + Assert.HasCount(1, _attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments); + Assert.HasCount(1, _attachmentManager.AttachmentSets[datacollectioncontext][uri1].Attachments); } [TestMethod] @@ -222,7 +224,7 @@ public void AddAttachmentShouldAddNewFileTransferAndMoveFileToOutputDirectoryIfD // Wait for file operations to complete waitHandle.WaitOne(Timeout); - Assert.AreEqual(1, _attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count); + Assert.HasCount(1, _attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments); Assert.IsTrue(File.Exists(Path.Combine(TempDirectoryPath, _sessionId.Id.ToString(), filename))); Assert.IsFalse(File.Exists(Path.Combine(TempDirectoryPath, filename))); } @@ -257,7 +259,7 @@ public void AddAttachmentShouldAddMultipleAttachmentsForSameDc() // Wait for file operations to complete waitHandle.WaitOne(Timeout); - Assert.AreEqual(2, _attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments.Count); + Assert.HasCount(2, _attachmentManager.AttachmentSets[datacollectioncontext][uri].Attachments); } [TestMethod] @@ -282,14 +284,14 @@ public void GetAttachmentsShouldReturnAllAttachments() _attachmentManager.AddAttachment(dataCollectorDataMessage, null, uri, friendlyName); - Assert.AreEqual(1, _attachmentManager.AttachmentSets.Count); + Assert.HasCount(1, _attachmentManager.AttachmentSets); var result = _attachmentManager.GetAttachments(datacollectioncontext); - Assert.AreEqual(0, _attachmentManager.AttachmentSets.Count); - Assert.AreEqual(1, result.Count); + Assert.IsEmpty(_attachmentManager.AttachmentSets); + Assert.HasCount(1, result); Assert.AreEqual(friendlyName, result[0].DisplayName); Assert.AreEqual(uri, result[0].Uri); - Assert.AreEqual(1, result[0].Attachments.Count); + Assert.HasCount(1, result[0].Attachments); } [TestMethod] @@ -300,7 +302,7 @@ public void GetAttachmentsShouldNotReturnAnyDataWhenActiveFileTransferAreNotPres var datacollectioncontext = new DataCollectionContext(_sessionId); var result = _attachmentManager.GetAttachments(datacollectioncontext); - Assert.AreEqual(0, result.Count); + Assert.IsEmpty(result); } [TestMethod] @@ -326,7 +328,7 @@ public void GetAttachmentsShouldNotReturnAttachmentsAfterCancelled() // Wait for the attachment transfer tasks to complete var result = testableAttachmentManager.GetAttachments(datacollectioncontext); - Assert.AreEqual(0, result[0].Attachments.Count); + Assert.IsEmpty(result[0].Attachments); } private class TestableDataCollectionAttachmentManager : DataCollectionAttachmentManager diff --git a/test/datacollector.UnitTests/DataCollectionManagerTests.cs b/test/datacollector.UnitTests/DataCollectionManagerTests.cs index 17ef4fb3b1..ca6407d98e 100644 --- a/test/datacollector.UnitTests/DataCollectionManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionManagerTests.cs @@ -69,7 +69,7 @@ public void InitializeDataCollectorsShouldReturnEmptyDictionaryIfDataCollectorsA var runSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Empty); _dataCollectionManager.InitializeDataCollectors(runSettings); - Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); + Assert.IsEmpty(_dataCollectionManager.RunDataCollectors); } [TestMethod] @@ -80,7 +80,7 @@ public void InitializeDataCollectorsShouldLoadDataCollector() Assert.IsTrue(_dataCollectionManager.RunDataCollectors.ContainsKey(_mockDataCollector.Object.GetType())); Assert.AreEqual(typeof(AttachmentProcessorDataCollector2), _dataCollectionManager.RunDataCollectors[_mockDataCollector.Object.GetType()].DataCollectorConfig.AttachmentsProcessorType); - Assert.IsTrue(_dataCollectionManager.RunDataCollectors[_mockDataCollector.Object.GetType()].DataCollectorConfig.Metadata.Contains(true)); + Assert.Contains(true, _dataCollectionManager.RunDataCollectors[_mockDataCollector.Object.GetType()].DataCollectorConfig.Metadata); _mockDataCollector.Verify(x => x.Initialize(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); } @@ -90,7 +90,7 @@ public void InitializeShouldNotAddDataCollectorIfItIsDisabled() var dataCollectorSettingsDisabled = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).Assembly.Location, "enabled=\"false\"")); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsDisabled); - Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); + Assert.IsEmpty(_dataCollectionManager.RunDataCollectors); _mockDataCollector.Verify(x => x.Initialize(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } @@ -111,7 +111,7 @@ public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsNotCo var dataCollectorSettingsWithWrongFriendlyName = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, "anyFriendlyName", _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).Assembly.Location, string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithWrongFriendlyName); - Assert.AreEqual(1, _dataCollectionManager.RunDataCollectors.Count); + Assert.HasCount(1, _dataCollectionManager.RunDataCollectors); _mockDataCollector.Verify(x => x.Initialize(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); _mockDataCollector.Verify(x => x.Initialize(_mockTelemetryReporter.Object), Times.Once); } @@ -122,7 +122,7 @@ public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsCorre var dataCollectorSettingsWithWrongUri = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, "my://custom/WrongDatacollector", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).Assembly.Location, string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithWrongUri); - Assert.AreEqual(1, _dataCollectionManager.RunDataCollectors.Count); + Assert.HasCount(1, _dataCollectionManager.RunDataCollectors); _mockDataCollector.Verify(x => x.Initialize(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); _mockDataCollector.Verify(x => x.Initialize(_mockTelemetryReporter.Object), Times.Once); } @@ -133,7 +133,7 @@ public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsNullA var dataCollectorSettingsWithNullFriendlyName = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, string.Empty, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).Assembly.Location, string.Empty).Replace("friendlyName=\"\"", string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithNullFriendlyName); - Assert.AreEqual(1, _dataCollectionManager.RunDataCollectors.Count); + Assert.HasCount(1, _dataCollectionManager.RunDataCollectors); _mockDataCollector.Verify(x => x.Initialize(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); _mockDataCollector.Verify(x => x.Initialize(_mockTelemetryReporter.Object), Times.Once); } @@ -158,7 +158,7 @@ public void InitializeDataCollectorsShouldNotLoadDataCollectorIfFriendlyNameIsNo var dataCollectorSettingsWithWrongFriendlyNameAndWrongUri = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, "anyFriendlyName", "datacollector://data", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).Assembly.Location, string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithWrongFriendlyNameAndWrongUri); - Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); + Assert.IsEmpty(_dataCollectionManager.RunDataCollectors); _mockDataCollector.Verify(x => x.Initialize(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } @@ -200,7 +200,7 @@ public void InitializeDataCollectorsShouldLogExceptionToMessageSinkIfInitializat _dataCollectionManager.InitializeDataCollectors(_dataCollectorSettings); - Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); + Assert.IsEmpty(_dataCollectionManager.RunDataCollectors); _mockMessageSink.Verify(x => x.SendMessage(It.IsAny()), Times.Once); } @@ -211,7 +211,7 @@ public void InitializeDataCollectorsShouldLogExceptionToMessageSinkIfSetEnvironm _dataCollectionManager.InitializeDataCollectors(_dataCollectorSettings); - Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); + Assert.IsEmpty(_dataCollectionManager.RunDataCollectors); _mockMessageSink.Verify(x => x.SendMessage(It.IsAny()), Times.Once); } @@ -244,7 +244,7 @@ public void InitializeDataCollectorsShouldReturnOtherThanCodeCoverageEnvironment var result = _dataCollectionManager.InitializeDataCollectors(_dataCollectorSettings); - Assert.AreEqual(3, result.Count); + Assert.HasCount(3, result); Assert.AreEqual("clrie", result["cor_profiler"]); Assert.AreEqual("path", result["clrie_profiler_vanguard"]); Assert.AreEqual("same_value", result["same_key"]); @@ -340,7 +340,7 @@ public void SessionEndedShouldReturnEmptyCollectionIfDataCollectionIsNotEnabled( var result = _dataCollectionManager.SessionEnded(); - Assert.AreEqual(0, result.Count); + Assert.IsEmpty(result); } [TestMethod] @@ -349,7 +349,7 @@ public void GetInvokedDataCollectorsShouldReturnDataCollector() var dataCollectorSettingsWithNullFriendlyName = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, string.Empty, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).Assembly.Location, string.Empty).Replace("friendlyName=\"\"", string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithNullFriendlyName); var invokedDataCollector = _dataCollectionManager.GetInvokedDataCollectors(); - Assert.AreEqual(1, invokedDataCollector.Count); + Assert.HasCount(1, invokedDataCollector); Assert.IsTrue(invokedDataCollector[0].HasAttachmentProcessor); } @@ -367,7 +367,7 @@ public void SessionEndedShouldReturnAttachments() var result = _dataCollectionManager.SessionEnded(); - Assert.IsTrue(result[0].Attachments[0].Uri.ToString().Contains("filename.txt")); + Assert.Contains("filename.txt", result[0].Attachments[0].Uri.ToString()); } [TestMethod] @@ -378,7 +378,7 @@ public void SessionEndedShouldNotReturnAttachmentsIfExceptionIsThrownWhileGettin var result = _dataCollectionManager.SessionEnded(); - Assert.AreEqual(0, result.Count); + Assert.IsEmpty(result); } [TestMethod] @@ -402,7 +402,7 @@ public void SessionEndedShouldContinueDataCollectionIfExceptionIsThrownWhileSend var result = _dataCollectionManager.SessionEnded(); - Assert.AreEqual(1, result.Count); + Assert.HasCount(1, result); } [TestMethod] diff --git a/test/testhost.UnitTests/AppDomainEngineInvokerTests.cs b/test/testhost.UnitTests/AppDomainEngineInvokerTests.cs index 81b1b9da2c..b715544586 100644 --- a/test/testhost.UnitTests/AppDomainEngineInvokerTests.cs +++ b/test/testhost.UnitTests/AppDomainEngineInvokerTests.cs @@ -102,7 +102,7 @@ public void AppDomainEngineInvokerShouldUseTestHostStartupConfigAndRuntimeAfterM Assert.AreEqual(legacyUnhandledEleExpectedXml, runtimeEle.Descendants("legacyUnhandledExceptionPolicy").First()?.ToString(), "legacyUnhandledExceptionPolicy element must be of the TestHost one."); - Assert.IsFalse(runtimeEle.ToString().Contains("probing"), "Probing element of TestHost must not be present."); + Assert.DoesNotContain("probing", runtimeEle.ToString(), "Probing element of TestHost must not be present."); var assemblyBindingXName = XName.Get("assemblyBinding", XmlNamespace); var mergedDocAssemblyBindingNodes = runtimeEle.Descendants(assemblyBindingXName); @@ -111,7 +111,7 @@ public void AppDomainEngineInvokerShouldUseTestHostStartupConfigAndRuntimeAfterM var dependentAssemblyXName = XName.Get("dependentAssembly", XmlNamespace); var dependentAssemblyNodes = mergedDocAssemblyBindingNodes.First().Descendants(dependentAssemblyXName); Assert.AreEqual(1, dependentAssemblyNodes.Count(), "AssemblyRedirect of TestHost must be present."); - Assert.IsTrue(dependentAssemblyNodes.First().ToString().Contains("Microsoft.VisualStudio.TestPlatform.ObjectModel"), "Correct AssemblyRedirect must be present."); + Assert.Contains("Microsoft.VisualStudio.TestPlatform.ObjectModel", dependentAssemblyNodes.First().ToString(), "Correct AssemblyRedirect must be present."); var diagEle = doc.Descendants("system.diagnostics").FirstOrDefault(); var appSettingsEle = doc.Descendants("appSettings").FirstOrDefault(); @@ -155,8 +155,8 @@ public void AppDomainEngineInvokerShouldOnlyMergeAssemblyRedirectionsFromTestHos var dependentAssemblyNodes = mergedDocAssemblyBindingNodes.First().Descendants(dependentAssemblyXName); Assert.AreEqual(2, dependentAssemblyNodes.Count(), "AssemblyBinding of TestHost must be present."); - Assert.IsTrue(dependentAssemblyNodes.ElementAt(0).ToString().Contains("Microsoft.VisualStudio.UnitTests"), "First AssemblyRedirect must be of UserConfig."); - Assert.IsTrue(dependentAssemblyNodes.ElementAt(1).ToString().Contains("Microsoft.VisualStudio.TestPlatform.ObjectModel"), "Second AssemblyRedirect must be from TestHost Node."); + Assert.Contains("Microsoft.VisualStudio.UnitTests", dependentAssemblyNodes.ElementAt(0).ToString(), "First AssemblyRedirect must be of UserConfig."); + Assert.Contains("Microsoft.VisualStudio.TestPlatform.ObjectModel", dependentAssemblyNodes.ElementAt(1).ToString(), "Second AssemblyRedirect must be from TestHost Node."); var diagEle = doc.Descendants("system.diagnostics").FirstOrDefault(); var appSettingsEle = doc.Descendants("appSettings").FirstOrDefault(); diff --git a/test/testhost.UnitTests/UnitTestClientTests.cs b/test/testhost.UnitTests/UnitTestClientTests.cs index 4296332eef..2a78255e18 100644 --- a/test/testhost.UnitTests/UnitTestClientTests.cs +++ b/test/testhost.UnitTests/UnitTestClientTests.cs @@ -22,7 +22,7 @@ public void SplitArgumentsShouldHonorDoubleQuotes() var argument = "--port 8080 --endpoint 127.0.0.1:8020 --diag \"abc txt\""; string[] argsArr = UnitTestClient.SplitArguments(argument); - Assert.AreEqual(6, argsArr.Length); + Assert.HasCount(6, argsArr); CollectionAssert.AreEqual(argsArr, expected); } @@ -33,7 +33,7 @@ public void SplitArgumentsShouldHonorSingleQuotes() var argument = "--port 8080 --endpoint 127.0.0.1:8020 --diag \'abc txt\'"; string[] argsArr = UnitTestClient.SplitArguments(argument); - Assert.AreEqual(6, argsArr.Length); + Assert.HasCount(6, argsArr); CollectionAssert.AreEqual(expected, argsArr); } @@ -44,7 +44,7 @@ public void SplitArgumentsShouldSplitAtSpacesOutsideOfQuotes() var argument = "--port 8080 --endpoint 127.0.0.1:8020 --diag abc txt"; string[] argsArr = UnitTestClient.SplitArguments(argument); - Assert.AreEqual(7, argsArr.Length); + Assert.HasCount(7, argsArr); CollectionAssert.AreEqual(expected, argsArr); } diff --git a/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs b/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs index c03e9bc02a..b35684b3a9 100644 --- a/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs +++ b/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs @@ -130,7 +130,7 @@ public void AutoDetectArchitectureShouldPopulateSourceArchitectureDictionary() .Returns(Architecture.AnyCPU).Returns(Architecture.X64).Returns(Architecture.X86); Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "x64.exe", "x86.dll" }, _defaultArchitecture, out var sourceArchitectures)); - Assert.AreEqual(3, sourceArchitectures.Count); + Assert.HasCount(3, sourceArchitectures); Assert.AreEqual(_defaultArchitecture, sourceArchitectures["AnyCPU1.dll"]); Assert.AreEqual(Architecture.X64, sourceArchitectures["x64.exe"]); Assert.AreEqual(Architecture.X86, sourceArchitectures["x86.dll"]); @@ -240,7 +240,7 @@ public void AutoDetectFrameworkShouldPopulatetheDictionaryForAllTheSources() Assert.AreEqual(_frameworkNet47.Name, _inferHelper.AutoDetectFramework(new List() { "net46.dll", "net47.exe", "net45.dll" }, out var sourceFrameworks).Name); - Assert.AreEqual(3, sourceFrameworks.Count); + Assert.HasCount(3, sourceFrameworks); Assert.AreEqual(_frameworkNet46.Name, sourceFrameworks["net46.dll"].Name); Assert.AreEqual(_frameworkNet47.Name, sourceFrameworks["net47.exe"].Name); Assert.AreEqual(_frameworkNet45.Name, sourceFrameworks["net45.dll"].Name); diff --git a/test/vstest.console.UnitTests/ExceptionUtilities.cs b/test/vstest.console.UnitTests/ExceptionUtilities.cs deleted file mode 100644 index 196abb3c4f..0000000000 --- a/test/vstest.console.UnitTests/ExceptionUtilities.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Globalization; - -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Microsoft.VisualStudio.TestPlatform.CommandLine.UnitTests; - -/// -/// This only exists because there is an issue with MSTest v2 and ThrowsException with a message API. -/// Move to Assert.ThrowException() with a message once the bug is fixed. -/// -public static class ExceptionUtilities -{ - public static void ThrowsException(Action action, string format, params string[] args) - { - var isExceptionThrown = false; - - try - { - action(); - } - catch (Exception ex) - { - Assert.AreEqual(typeof(T), ex.GetType()); - isExceptionThrown = true; - var message = string.Format(CultureInfo.CurrentCulture, format, args); - StringAssert.Contains(ex.Message, message); - } - - Assert.IsTrue(isExceptionThrown, "No Exception Thrown"); - } -} diff --git a/test/vstest.console.UnitTests/ExecutorUnitTests.cs b/test/vstest.console.UnitTests/ExecutorUnitTests.cs index 313ec26a25..2310fde6dd 100644 --- a/test/vstest.console.UnitTests/ExecutorUnitTests.cs +++ b/test/vstest.console.UnitTests/ExecutorUnitTests.cs @@ -46,16 +46,16 @@ public void ExecutorPrintsSplashScreenTest() Assert.AreEqual(1, exitCode, "Exit code must be One for bad arguments"); // Verify that messages exist - Assert.IsTrue(mockOutput.Messages.Count > 0, "Executor must print at least copyright info"); + Assert.IsNotEmpty(mockOutput.Messages, "Executor must print at least copyright info"); Assert.IsNotNull(mockOutput.Messages.First().Message, "First Printed Message cannot be null or empty"); - StringAssert.Contains(mockOutput.Messages.First().Message, - CommandLineResources.MicrosoftCommandLineTitle.Split(['{'], 2)[0]); + Assert.Contains(CommandLineResources.MicrosoftCommandLineTitle.Split(['{'], 2)[0], + mockOutput.Messages.First().Message!); var suffixIndex = assemblyVersion.IndexOf("-"); var version = suffixIndex == -1 ? assemblyVersion : assemblyVersion.Substring(0, suffixIndex); - StringAssert.Contains(mockOutput.Messages.First().Message, - version); + Assert.Contains(version, + mockOutput.Messages.First().Message!); } [TestMethod] @@ -67,12 +67,13 @@ public void ExecutorShouldNotPrintsSplashScreenIfNoLogoPassed() Assert.AreEqual(1, exitCode, "Exit code must be One for bad arguments"); // Verify that messages exist - Assert.IsTrue(mockOutput.Messages.Count == 1, "Executor should not print no valid arguments provided"); + Assert.HasCount(1, mockOutput.Messages); // Check the part of message before the actual version because that is variable. - Assert.IsFalse( + Assert.DoesNotContain( + CommandLineResources.MicrosoftCommandLineTitle.Split(['{'], 2)[0], mockOutput.Messages.First() - .Message!.Contains(CommandLineResources.MicrosoftCommandLineTitle.Split(['{'], 2)[0])); + .Message!); } [TestMethod] @@ -83,7 +84,7 @@ public void ExecutorShouldSanitizeNoLogoInput() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(CommandLineResources.NoArgumentsProvided))); + Assert.Contains(message => message.Message!.Contains(CommandLineResources.NoArgumentsProvided), mockOutput.Messages); } /// @@ -97,7 +98,7 @@ public void ExecutorEmptyArgsPrintsErrorAndHelpMessage() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(CommandLineResources.NoArgumentsProvided))); + Assert.Contains(message => message.Message!.Contains(CommandLineResources.NoArgumentsProvided), mockOutput.Messages); } [TestMethod] @@ -109,7 +110,7 @@ public void ExecutorWithInvalidArgsShouldPrintErrorMessage() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)))); + Assert.Contains(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)), mockOutput.Messages); } [TestMethod] @@ -121,7 +122,7 @@ public void ExecutorWithInvalidArgsShouldPrintHowToUseHelpOption() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)))); + Assert.Contains(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)), mockOutput.Messages); } [TestMethod] @@ -133,7 +134,7 @@ public void ExecutorWithInvalidArgsAndValueShouldPrintErrorMessage() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)))); + Assert.Contains(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)), mockOutput.Messages); } /// @@ -197,7 +198,7 @@ public void ExecutorShouldPrintDotnetVSTestDeprecationMessage(string commandLine new Executor(mockOutput, _mockTestPlatformEventSource.Object, processHelper.Object, environment.Object).Execute(commandLine); - Assert.AreEqual(5, mockOutput.Messages.Count); + Assert.HasCount(5, mockOutput.Messages); Assert.AreEqual(OutputLevel.Warning, mockOutput.Messages[2].Level); Assert.AreEqual("The dotnet vstest command is superseded by dotnet test, which can now be used to run assemblies. See https://aka.ms/dotnet-test.", mockOutput.Messages[2].Message); } @@ -330,7 +331,7 @@ public void ExecutorShouldPrintWarningIfRunningEmulatedOnARM64() var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, processHelper.Object, environment.Object).Execute(); var assemblyVersion = typeof(Executor).Assembly.GetCustomAttribute()!.InformationalVersion; - Assert.AreEqual(4, mockOutput.Messages.Count); + Assert.HasCount(4, mockOutput.Messages); Assert.AreEqual("vstest.console.exe is running in emulated mode as x64. For better performance, please consider using the native runner vstest.console.arm64.exe.", mockOutput.Messages[1].Message); Assert.AreEqual(OutputLevel.Warning, @@ -350,9 +351,9 @@ public void ExecutorShouldPrintRunnerArchitecture() var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, processHelper.Object, environment.Object).Execute(); var assemblyVersion = typeof(Executor).Assembly.GetCustomAttribute()!.InformationalVersion; - Assert.AreEqual(3, mockOutput.Messages.Count); - Assert.IsTrue(Regex.IsMatch(mockOutput.Messages[0].Message!, @"VSTest version .* \(x64\)")); - Assert.IsFalse(mockOutput.Messages.Any(message => message.Message!.Contains("vstest.console.exe is running in emulated mode"))); + Assert.HasCount(3, mockOutput.Messages); + Assert.MatchesRegex(@"VSTest version .* \(x64\)", mockOutput.Messages[0].Message!); + Assert.DoesNotContain(message => message.Message!.Contains("vstest.console.exe is running in emulated mode"), mockOutput.Messages); } private class MockOutput : IOutput diff --git a/test/vstest.console.UnitTests/InProcessVsTestConsoleWrapperTests.cs b/test/vstest.console.UnitTests/InProcessVsTestConsoleWrapperTests.cs index c57e7d28a3..57eacd4918 100644 --- a/test/vstest.console.UnitTests/InProcessVsTestConsoleWrapperTests.cs +++ b/test/vstest.console.UnitTests/InProcessVsTestConsoleWrapperTests.cs @@ -116,9 +116,9 @@ public void InProcessWrapperConstructorShouldSetEnvironmentVariablesReceivedAsCo new Mock().Object, new()); - Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?.Count == 1); + Assert.AreEqual(1, ProcessHelper.ExternalEnvironmentVariables?.Count); Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?.ContainsKey(environmentVariableName)); - Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?[environmentVariableName] == "1"); + Assert.AreEqual("1", ProcessHelper.ExternalEnvironmentVariables?[environmentVariableName]); } [TestMethod] @@ -147,13 +147,13 @@ public void InProcessWrapperConstructorShouldSetEnvironmentVariablesReceivedAsCo new Mock().Object, new()); - Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?.Count == 3); + Assert.AreEqual(3, ProcessHelper.ExternalEnvironmentVariables?.Count); Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?.ContainsKey(environmentVariableName1)); - Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?[environmentVariableName1] == "1"); + Assert.AreEqual("1", ProcessHelper.ExternalEnvironmentVariables?[environmentVariableName1]); Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?.ContainsKey(environmentVariableName2)); - Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?[environmentVariableName2] == "1"); + Assert.AreEqual("1", ProcessHelper.ExternalEnvironmentVariables?[environmentVariableName2]); Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?.ContainsKey(environmentVariableName3)); - Assert.IsTrue(ProcessHelper.ExternalEnvironmentVariables?[environmentVariableName3] == "1"); + Assert.AreEqual("1", ProcessHelper.ExternalEnvironmentVariables?[environmentVariableName3]); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Internal/FilePatternParserTests.cs b/test/vstest.console.UnitTests/Internal/FilePatternParserTests.cs index 7956373252..ed65d73e99 100644 --- a/test/vstest.console.UnitTests/Internal/FilePatternParserTests.cs +++ b/test/vstest.console.UnitTests/Internal/FilePatternParserTests.cs @@ -101,7 +101,7 @@ public void FilePatternParserShouldCheckIfFileExistsIfFullPathGiven() // Assert _mockFileHelper.Verify(x => x.Exists(TranslatePath(@"E:\path\to\project\tests\Blame.Tests\\abc.Tests.dll"))); - Assert.IsTrue(matchingFiles.Contains(TranslatePath(@"E:\path\to\project\tests\Blame.Tests\\abc.Tests.dll"))); + Assert.Contains(TranslatePath(@"E:\path\to\project\tests\Blame.Tests\\abc.Tests.dll"), matchingFiles); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs index d594a7246d..181517cfa5 100644 --- a/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs @@ -7,9 +7,9 @@ using Microsoft.VisualStudio.TestPlatform.CommandLine; using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors; -using Microsoft.VisualStudio.TestPlatform.CommandLine.UnitTests; using Microsoft.VisualStudio.TestPlatform.Common; using Microsoft.VisualStudio.TestPlatform.ObjectModel; +using Microsoft.VisualStudio.TestPlatform.CommandLine.UnitTests; using Microsoft.VisualStudio.TestTools.UnitTesting; using CommandLineResources = Microsoft.VisualStudio.TestPlatform.CommandLine.Resources.Resources; @@ -178,11 +178,8 @@ public void InitializeShouldIgnoreThrowExceptionIfKeyHasWhiteSpace() { var args = new string[] { "MST est.DeploymentEnabled=False" }; - Action action = () => _executor.Initialize(args); - - ExceptionUtilities.ThrowsException( - action, - "One or more runsettings provided contain invalid token"); + var ex = Assert.ThrowsExactly(() => _executor.Initialize(args)); + Assert.Contains("One or more runsettings provided contain invalid token", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs index 956c67ccc7..57f2d0afce 100644 --- a/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs @@ -114,21 +114,10 @@ public void InitializeShouldThrowExceptionWhenTestSettingsIsEnabled() runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); - bool exceptionThrown = false; - - try - { - _executor.Initialize("MyDataCollector"); - } - catch (SettingsException ex) - { - exceptionThrown = true; - Assert.AreEqual( - "--Collect|/Collect:\"MyDataCollector\" is not supported if test run is configured using testsettings.", - ex.Message); - } - - Assert.IsTrue(exceptionThrown, "Initialize should throw exception"); + var ex = Assert.ThrowsExactly(() => _executor.Initialize("MyDataCollector")); + Assert.AreEqual( + "--Collect|/Collect:\"MyDataCollector\" is not supported if test run is configured using testsettings.", + ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs index 405fee6e19..a541cbdcc6 100644 --- a/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs @@ -101,7 +101,7 @@ public void InitializeShouldCreateEntryForCodeCoverageInRunSettingsIfNotAlreadyP var dataCollectorsFriendlyNames = XmlRunSettingsUtilities.GetDataCollectorsFriendlyName(_settingsProvider.ActiveRunSettings .SettingsXml!); - Assert.IsTrue(dataCollectorsFriendlyNames.Contains("Code Coverage"), + Assert.Contains("Code Coverage", dataCollectorsFriendlyNames, "Code coverage setting in not available in runsettings"); } diff --git a/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs index 1a1098dfbc..e6766808e3 100644 --- a/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs @@ -118,14 +118,7 @@ public void EnableDiagArgumentProcessorExecutorShouldThrowIfInvalidArgument(stri [DataRow("log.log")] public void EnableDiagArgumentProcessorExecutorShouldNotThrowIfValidArgument(string argument) { - try - { - _diagProcessor.Executor!.Value.Initialize(argument); - } - catch (Exception ex) - { - Assert.Fail("Expected no exception, but got: " + ex.Message); - } + _diagProcessor.Executor!.Value.Initialize(argument); } [TestMethod] @@ -179,6 +172,6 @@ public TestableEnableDiagArgumentProcessor(IFileHelper fileHelper) private void EnableDiagArgumentProcessorExecutorShouldThrowIfInvalidArgument(string argument, string exceptionMessage) { var e = Assert.ThrowsExactly(() => _diagProcessor.Executor!.Value.Initialize(argument)); - StringAssert.Contains(e.Message, exceptionMessage); + Assert.Contains(exceptionMessage, e.Message); } } diff --git a/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs index 40ef827514..53afbc8680 100644 --- a/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs @@ -62,16 +62,10 @@ public void CapabilitiesShouldAppropriateProperties() public void ExectorInitializeShouldThrowExceptionIfInvalidArgumentIsPassed(string argument) { var executor = new EnableLoggerArgumentExecutor(RunSettingsManager.Instance); - try - { - executor.Initialize(argument); - } - catch (Exception e) - { - string exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.LoggerUriInvalid, argument); - Assert.IsTrue(e.GetType().Equals(typeof(CommandLineException))); - Assert.IsTrue(e.Message.Contains(exceptionMessage)); - } + var e = Assert.ThrowsExactly(() => executor.Initialize(argument)); + string exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.LoggerUriInvalid, argument); + Assert.IsInstanceOfType(e); + Assert.Contains(exceptionMessage, e.Message); } [TestMethod] @@ -241,7 +235,7 @@ public void ExecutorInitializeShouldCorrectlyAddLoggerWhenRunSettingsNotPassed() "; - Assert.IsTrue(RunSettingsManager.Instance.ActiveRunSettings!.SettingsXml!.Contains(expectedSettingsXml)); + Assert.Contains(expectedSettingsXml, RunSettingsManager.Instance.ActiveRunSettings!.SettingsXml!); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs index dd19bc886f..4c827f9d77 100644 --- a/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs @@ -76,7 +76,7 @@ public void AppendsEnvironmentVariableToRunSettings() Assert.IsNotNull(inIsolation, "Isolation must be forced, an InIsolation entry was missing!"); var variables = environmentVariables.Elements().ToArray(); - Assert.AreEqual(1, variables.Length, "Environment variable count mismatched!"); + Assert.HasCount(1, variables); Assert.AreEqual("true", inIsolation.Value, "Isolation must be forced, InIsolation is not set to true."); Assert.AreEqual("VARIABLE", variables[0].Name.LocalName); @@ -107,7 +107,7 @@ public void AppendsMultipleEnvironmentVariablesToRunSettings() Assert.AreEqual("true", inIsolation.Value, "Isolation must be forced, InIsolation is not set to true."); var variables = environmentVariables.Elements().ToArray(); - Assert.AreEqual(3, variables.Length, "Environment variable count mismatched!"); + Assert.HasCount(3, variables); Assert.AreEqual("VARIABLE_ONE", variables[0].Name.LocalName); Assert.AreEqual("VALUE", variables[0].Value); @@ -140,7 +140,7 @@ public void InIsolationValueShouldBeOverriden() Assert.AreEqual("true", inIsolation.Value, "Isolation must be forced, InIsolation is overriden to true."); var variables = environmentVariables.Elements().ToArray(); - Assert.AreEqual(1, variables.Length, "Environment variable count mismatched!"); + Assert.HasCount(1, variables); Assert.AreEqual("VARIABLE", variables[0].Name.LocalName); Assert.AreEqual("VALUE", variables[0].Value); diff --git a/test/vstest.console.UnitTests/Processors/FrameworkArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/FrameworkArgumentProcessorTests.cs index 69d8e91974..35a7c8396e 100644 --- a/test/vstest.console.UnitTests/Processors/FrameworkArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/FrameworkArgumentProcessorTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Globalization; + using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors; using Microsoft.VisualStudio.TestPlatform.Common.Utilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -48,7 +50,7 @@ public void CapabilitiesShouldReturnAppropriateProperties() { var capabilities = new FrameworkArgumentProcessorCapabilities(); Assert.AreEqual("/Framework", capabilities.CommandName); - StringAssert.Contains(capabilities.HelpContentResourceName, "Valid values are \".NETFramework,Version=v4.5.1\", \".NETCoreApp,Version=v1.0\""); + Assert.Contains("Valid values are \".NETFramework,Version=v4.5.1\", \".NETCoreApp,Version=v1.0\"", capabilities.HelpContentResourceName); Assert.AreEqual(HelpContentPriority.FrameworkArgumentProcessorHelpPriority, capabilities.HelpPriority); Assert.IsFalse(capabilities.IsAction); @@ -67,26 +69,22 @@ public void CapabilitiesShouldReturnAppropriateProperties() public void InitializeShouldThrowIfArgumentIsNull() { - ExceptionUtilities.ThrowsException( - () => _executor.Initialize(null), - "The /Framework argument requires the target .Net Framework version for the test run. Example: /Framework:\".NETFramework,Version=v4.5.1\""); + var ex = Assert.ThrowsExactly(() => _executor.Initialize(null)); + Assert.Contains("The /Framework argument requires the target .Net Framework version for the test run. Example: /Framework:\".NETFramework,Version=v4.5.1\"", ex.Message); } [TestMethod] public void InitializeShouldThrowIfArgumentIsEmpty() { - ExceptionUtilities.ThrowsException( - () => _executor.Initialize(" "), - "The /Framework argument requires the target .Net Framework version for the test run. Example: /Framework:\".NETFramework,Version=v4.5.1\""); + var ex = Assert.ThrowsExactly(() => _executor.Initialize(" ")); + Assert.Contains("The /Framework argument requires the target .Net Framework version for the test run. Example: /Framework:\".NETFramework,Version=v4.5.1\"", ex.Message); } [TestMethod] public void InitializeShouldThrowIfArgumentIsInvalid() { - ExceptionUtilities.ThrowsException( - () => _executor.Initialize("foo"), - "Invalid .Net Framework version:{0}. Please give the fullname of the TargetFramework(Example: .NETCoreApp,Version=v2.0). Other supported .Net Framework versions are Framework40, Framework45, FrameworkCore10 and FrameworkUap10.", - "foo"); + var ex = Assert.ThrowsExactly(() => _executor.Initialize("foo")); + Assert.Contains(string.Format(CultureInfo.CurrentCulture, "Invalid .Net Framework version:{0}. Please give the fullname of the TargetFramework(Example: .NETCoreApp,Version=v2.0). Other supported .Net Framework versions are Framework40, Framework45, FrameworkCore10 and FrameworkUap10.", "foo"), ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/HelpArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/HelpArgumentProcessorTests.cs index 333d6ece1c..e39f6feedd 100644 --- a/test/vstest.console.UnitTests/Processors/HelpArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/HelpArgumentProcessorTests.cs @@ -69,11 +69,11 @@ public void ExecuterExecuteWritesAppropriateDataToConsole() var output = new DummyConsoleOutput(); executor.Output = output; _ = executor.Execute(); - Assert.IsTrue(output.Lines.Contains("Usage: vstest.console.exe [Arguments] [Options] [[--] ...]]")); - Assert.IsTrue(output.Lines.Contains("Arguments:")); - Assert.IsTrue(output.Lines.Contains("Options:")); - Assert.IsTrue(output.Lines.Contains("Description: Runs tests from the specified files.")); - Assert.IsTrue(output.Lines.Contains(" To run tests:" + Environment.NewLine + " >vstest.console.exe tests.dll " + Environment.NewLine + " To run tests with additional settings such as data collectors:" + Environment.NewLine + " >vstest.console.exe tests.dll /Settings:Local.RunSettings")); + Assert.Contains("Usage: vstest.console.exe [Arguments] [Options] [[--] ...]]", output.Lines); + Assert.Contains("Arguments:", output.Lines); + Assert.Contains("Options:", output.Lines); + Assert.Contains("Description: Runs tests from the specified files.", output.Lines); + Assert.Contains(" To run tests:" + Environment.NewLine + " >vstest.console.exe tests.dll " + Environment.NewLine + " To run tests with additional settings such as data collectors:" + Environment.NewLine + " >vstest.console.exe tests.dll /Settings:Local.RunSettings", output.Lines); } } diff --git a/test/vstest.console.UnitTests/Processors/InIsolationArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/InIsolationArgumentProcessorTests.cs index 2889fe8e0f..49a4f07346 100644 --- a/test/vstest.console.UnitTests/Processors/InIsolationArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/InIsolationArgumentProcessorTests.cs @@ -62,9 +62,8 @@ public void InIsolationArgumentProcessorMetadataShouldProvideAppropriateCapabili public void InIsolationArgumentProcessorExecutorShouldThrowIfArgumentIsProvided() { // InProcess should not have any values or arguments - ExceptionUtilities.ThrowsException( - () => _executor.Initialize("true"), - "Argument true is not expected in the 'InIsolation' command. Specify the command without the argument (Example: vstest.console.exe myTests.dll /InIsolation) and try again."); + var ex = Assert.ThrowsExactly(() => _executor.Initialize("true")); + Assert.Contains("Argument true is not expected in the 'InIsolation' command. Specify the command without the argument (Example: vstest.console.exe myTests.dll /InIsolation) and try again.", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/ListFullyQualifiedTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ListFullyQualifiedTestsArgumentProcessorTests.cs index 256e4483b1..83159cdf58 100644 --- a/test/vstest.console.UnitTests/Processors/ListFullyQualifiedTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ListFullyQualifiedTestsArgumentProcessorTests.cs @@ -234,9 +234,9 @@ public void ExecutorExecuteShouldOutputDiscoveredTestsAndReturnSuccess() mockDiscoveryRequest.Verify(dr => dr.DiscoverAsync(), Times.Once); var fileOutput = File.ReadAllLines(_dummyFilePath); - Assert.IsTrue(fileOutput.Length == 2); - Assert.IsTrue(fileOutput.Contains("Test1")); - Assert.IsTrue(fileOutput.Contains("Test2")); + Assert.HasCount(2, fileOutput); + Assert.Contains("Test1", fileOutput); + Assert.Contains("Test2", fileOutput); } [TestMethod] @@ -250,9 +250,9 @@ public void DiscoveryShouldFilterCategoryTestsAndReturnSuccess() mockDiscoveryRequest.Verify(dr => dr.DiscoverAsync(), Times.Once); var fileOutput = File.ReadAllLines(_dummyFilePath); - Assert.IsTrue(fileOutput.Length == 1); - Assert.IsTrue(fileOutput.Contains("Test1")); - Assert.IsFalse(fileOutput.Contains("Test2")); + Assert.HasCount(1, fileOutput); + Assert.Contains("Test1", fileOutput); + Assert.DoesNotContain("Test2", fileOutput); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/ListTestsTargetPathArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ListTestsTargetPathArgumentProcessorTests.cs index b98f2db49c..9ed9f22bb6 100644 --- a/test/vstest.console.UnitTests/Processors/ListTestsTargetPathArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ListTestsTargetPathArgumentProcessorTests.cs @@ -49,15 +49,8 @@ public void ExecutorInitializeWithNullOrEmptyListTestsTargetPathShouldThrowComma var options = CommandLineOptions.Instance; ListTestsTargetPathArgumentExecutor executor = new(options); - try - { - executor.Initialize(null); - } - catch (Exception ex) - { - Assert.IsTrue(ex is CommandLineException); - StringAssert.Contains(ex.Message, "ListTestsTargetPath is required with ListFullyQualifiedTests!"); - } + var ex = Assert.ThrowsExactly(() => executor.Initialize(null)); + Assert.Contains("ListTestsTargetPath is required with ListFullyQualifiedTests!", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/ParallelArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ParallelArgumentProcessorTests.cs index 9e0580aa63..4d264812a5 100644 --- a/test/vstest.console.UnitTests/Processors/ParallelArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ParallelArgumentProcessorTests.cs @@ -68,9 +68,8 @@ public void InitializeShouldThrowIfArgumentIsNonNull() { // Parallel should not have any values or arguments - ExceptionUtilities.ThrowsException( - () => _executor.Initialize("123"), - "Argument " + 123 + " is not expected in the 'Parallel' command. Specify the command without the argument (Example: vstest.console.exe myTests.dll /Parallel) and try again."); + var ex = Assert.ThrowsExactly(() => _executor.Initialize("123")); + Assert.Contains("Argument " + 123 + " is not expected in the 'Parallel' command. Specify the command without the argument (Example: vstest.console.exe myTests.dll /Parallel) and try again.", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/ParentProcessIdArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ParentProcessIdArgumentProcessorTests.cs index 7624740e17..08ab0db5ad 100644 --- a/test/vstest.console.UnitTests/Processors/ParentProcessIdArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ParentProcessIdArgumentProcessorTests.cs @@ -30,10 +30,9 @@ public void GetExecutorShouldReturnParentProcessIdArgumentProcessorCapabilities( public void CapabilitiesShouldHaveHigherPriorityThanPortCapabilities() { var parentProcessIdCapabilities = new ParentProcessIdArgumentProcessorCapabilities(); - var portCapabilities = new PortArgumentProcessorCapabilities(); // Less the number, high the priority - Assert.IsTrue(parentProcessIdCapabilities.Priority == portCapabilities.Priority, "ParentProcessId must have higher priority than Port."); + Assert.AreEqual(ArgumentProcessorPriority.DesignMode, parentProcessIdCapabilities.Priority, "ParentProcessId must have higher priority than Port."); } [TestMethod] @@ -57,30 +56,16 @@ public void CapabilitiesShouldReturnAppropriateProperties() public void ExecutorInitializeWithNullOrEmptyParentProcessIdShouldThrowCommandLineException() { var executor = new ParentProcessIdArgumentExecutor(CommandLineOptions.Instance); - try - { - executor.Initialize(null); - } - catch (Exception ex) - { - Assert.IsTrue(ex is CommandLineException); - Assert.AreEqual("The --ParentProcessId|/ParentProcessId argument requires the process id which is an integer. Specify the process id of the parent process that launched this process.", ex.Message); - } + var ex = Assert.ThrowsExactly(() => executor.Initialize(null)); + Assert.AreEqual("The --ParentProcessId|/ParentProcessId argument requires the process id which is an integer. Specify the process id of the parent process that launched this process.", ex.Message); } [TestMethod] public void ExecutorInitializeWithInvalidParentProcessIdShouldThrowCommandLineException() { var executor = new ParentProcessIdArgumentExecutor(CommandLineOptions.Instance); - try - { - executor.Initialize("Foo"); - } - catch (Exception ex) - { - Assert.IsTrue(ex is CommandLineException); - Assert.AreEqual("The --ParentProcessId|/ParentProcessId argument requires the process id which is an integer. Specify the process id of the parent process that launched this process.", ex.Message); - } + var ex = Assert.ThrowsExactly(() => executor.Initialize("Foo")); + Assert.AreEqual("The --ParentProcessId|/ParentProcessId argument requires the process id which is an integer. Specify the process id of the parent process that launched this process.", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/PlatformArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/PlatformArgumentProcessorTests.cs index ce1c985c15..73f38ca8cd 100644 --- a/test/vstest.console.UnitTests/Processors/PlatformArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/PlatformArgumentProcessorTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Globalization; + using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors; using Microsoft.VisualStudio.TestPlatform.Common.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -67,35 +69,29 @@ public void CapabilitiesShouldReturnAppropriateProperties() [TestMethod] public void InitializeShouldThrowIfArgumentIsNull() { - ExceptionUtilities.ThrowsException( - () => _executor.Initialize(null), - "The /Platform argument requires the target platform type for the test run to be provided. Example: /Platform:x86"); + var ex = Assert.ThrowsExactly(() => _executor.Initialize(null)); + Assert.Contains("The /Platform argument requires the target platform type for the test run to be provided. Example: /Platform:x86", ex.Message); } [TestMethod] public void InitializeShouldThrowIfArgumentIsEmpty() { - ExceptionUtilities.ThrowsException( - () => _executor.Initialize(" "), - "The /Platform argument requires the target platform type for the test run to be provided. Example: /Platform:x86"); + var ex = Assert.ThrowsExactly(() => _executor.Initialize(" ")); + Assert.Contains("The /Platform argument requires the target platform type for the test run to be provided. Example: /Platform:x86", ex.Message); } [TestMethod] public void InitializeShouldThrowIfArgumentIsNotAnArchitecture() { - ExceptionUtilities.ThrowsException( - () => _executor.Initialize("foo"), - "Invalid platform type: {0}. Valid platform types are X86, X64, ARM, ARM64, S390x, Ppc64le, RiscV64, LoongArch64.", - "foo"); + var ex = Assert.ThrowsExactly(() => _executor.Initialize("foo")); + Assert.Contains(string.Format(CultureInfo.CurrentCulture, "Invalid platform type: {0}. Valid platform types are X86, X64, ARM, ARM64, S390x, Ppc64le, RiscV64, LoongArch64.", "foo"), ex.Message); } [TestMethod] public void InitializeShouldThrowIfArgumentIsNotASupportedArchitecture() { - ExceptionUtilities.ThrowsException( - () => _executor.Initialize("AnyCPU"), - "Invalid platform type: {0}. Valid platform types are X86, X64, ARM, ARM64, S390x, Ppc64le, RiscV64, LoongArch64.", - "AnyCPU"); + var ex = Assert.ThrowsExactly(() => _executor.Initialize("AnyCPU")); + Assert.Contains(string.Format(CultureInfo.CurrentCulture, "Invalid platform type: {0}. Valid platform types are X86, X64, ARM, ARM64, S390x, Ppc64le, RiscV64, LoongArch64.", "AnyCPU"), ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/PortArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/PortArgumentProcessorTests.cs index b0769764a0..09e78728de 100644 --- a/test/vstest.console.UnitTests/Processors/PortArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/PortArgumentProcessorTests.cs @@ -70,29 +70,15 @@ public void CapabilitiesShouldAppropriateProperties() [TestMethod] public void ExecutorInitializeWithNullOrEmptyPortShouldThrowCommandLineException() { - try - { - _executor.Initialize(null); - } - catch (Exception ex) - { - Assert.IsTrue(ex is CommandLineException); - Assert.AreEqual("The --Port|/Port argument requires the port number which is an integer. Specify the port for socket connection and receiving the event messages.", ex.Message); - } + var ex = Assert.ThrowsExactly(() => _executor.Initialize(null)); + Assert.AreEqual("The --Port|/Port argument requires the port number which is an integer. Specify the port for socket connection and receiving the event messages.", ex.Message); } [TestMethod] public void ExecutorInitializeWithInvalidPortShouldThrowCommandLineException() { - try - { - _executor.Initialize("Foo"); - } - catch (Exception ex) - { - Assert.IsTrue(ex is CommandLineException); - Assert.AreEqual("The --Port|/Port argument requires the port number which is an integer. Specify the port for socket connection and receiving the event messages.", ex.Message); - } + var ex = Assert.ThrowsExactly(() => _executor.Initialize("Foo")); + Assert.AreEqual("The --Port|/Port argument requires the port number which is an integer. Specify the port for socket connection and receiving the event messages.", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/ResponseFileArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ResponseFileArgumentProcessorTests.cs index 3c433aefe7..7f948c8aab 100644 --- a/test/vstest.console.UnitTests/Processors/ResponseFileArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ResponseFileArgumentProcessorTests.cs @@ -36,7 +36,7 @@ public void CapabilitiesShouldReturnAppropriateProperties() { var capabilities = new ResponseFileArgumentProcessorCapabilities(); Assert.AreEqual("@", capabilities.CommandName); - StringAssert.Contains(capabilities.HelpContentResourceName, "Read response file for more options"); + Assert.Contains("Read response file for more options", capabilities.HelpContentResourceName); Assert.AreEqual(HelpContentPriority.ResponseFileArgumentProcessorHelpPriority, capabilities.HelpPriority); Assert.IsFalse(capabilities.IsAction); diff --git a/test/vstest.console.UnitTests/Processors/ResultsDirectoryArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ResultsDirectoryArgumentProcessorTests.cs index bc5d345804..c1c9cdb2c9 100644 --- a/test/vstest.console.UnitTests/Processors/ResultsDirectoryArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ResultsDirectoryArgumentProcessorTests.cs @@ -108,20 +108,8 @@ public void InitializeShouldThrowIfGivenPathIsIllegal() private void InitializeExceptionTestTemplate(string? folder, string message) { - var isExceptionThrown = false; - - try - { - _executor.Initialize(folder); - } - catch (Exception ex) - { - isExceptionThrown = true; - Assert.IsTrue(ex is CommandLineException, "ex is CommandLineException"); - StringAssert.StartsWith(ex.Message, message); - } - - Assert.IsTrue(isExceptionThrown, "isExceptionThrown"); + var ex = Assert.ThrowsExactly(() => _executor.Initialize(folder)); + Assert.StartsWith(message, ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs index d32df8d4c1..be82e2687b 100644 --- a/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.IO; using System.Text; using System.Xml; @@ -76,21 +77,15 @@ public void CapabilitiesShouldReturnAppropriateProperties() [TestMethod] public void InitializeShouldThrowExceptionIfArgumentIsNull() { - Action action = () => new RunSettingsArgumentExecutor(CommandLineOptions.Instance, null!).Initialize(null); - - ExceptionUtilities.ThrowsException( - action, - "The /Settings parameter requires a settings file to be provided."); + var ex = Assert.ThrowsExactly(() => new RunSettingsArgumentExecutor(CommandLineOptions.Instance, null!).Initialize(null)); + Assert.Contains("The /Settings parameter requires a settings file to be provided.", ex.Message); } [TestMethod] public void InitializeShouldThrowExceptionIfArgumentIsWhiteSpace() { - Action action = () => new RunSettingsArgumentExecutor(CommandLineOptions.Instance, null!).Initialize(" "); - - ExceptionUtilities.ThrowsException( - action, - "The /Settings parameter requires a settings file to be provided."); + var ex = Assert.ThrowsExactly(() => new RunSettingsArgumentExecutor(CommandLineOptions.Instance, null!).Initialize(" ")); + Assert.Contains("The /Settings parameter requires a settings file to be provided.", ex.Message); } [TestMethod] @@ -104,10 +99,8 @@ public void InitializeShouldThrowExceptionIfFileDoesNotExist() executor.FileHelper = mockFileHelper.Object; - ExceptionUtilities.ThrowsException( - () => executor.Initialize(fileName), - "The Settings file '{0}' could not be found.", - fileName); + var ex = Assert.ThrowsExactly(() => executor.Initialize(fileName)); + Assert.Contains(string.Format(CultureInfo.CurrentCulture, "The Settings file '{0}' could not be found.", fileName), ex.Message); } [TestMethod] @@ -129,9 +122,8 @@ public void InitializeShouldThrowIfRunSettingsSchemaDoesNotMatch() executor.FileHelper = mockFileHelper.Object; // Act and Assert. - ExceptionUtilities.ThrowsException( - () => executor.Initialize(fileName), - "Settings file provided does not conform to required format."); + var ex = Assert.ThrowsExactly(() => executor.Initialize(fileName)); + Assert.Contains("Settings file provided does not conform to required format.", ex.Message); } [TestMethod] @@ -253,7 +245,7 @@ public void InitializeShouldSetActiveRunSettingsForTestSettingsFiles() $" ", $" ", $""); - StringAssert.Contains(_settingsProvider.ActiveRunSettings.SettingsXml, expected); + Assert.Contains(expected, _settingsProvider.ActiveRunSettings.SettingsXml!); } @@ -323,7 +315,7 @@ public void InitializeShouldPreserveActualJapaneseString() null); executor.Initialize(runsettingsFile); - Assert.IsTrue(_settingsProvider.ActiveRunSettings!.SettingsXml!.Contains(@"C:\新しいフォルダー")); + Assert.Contains(@"C:\新しいフォルダー", _settingsProvider.ActiveRunSettings!.SettingsXml!); File.Delete(runsettingsFile); } diff --git a/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs index a72e69af8c..6462c6a940 100644 --- a/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs @@ -101,8 +101,8 @@ public void CapabilitiesShouldReturnAppropriateProperties() { RunSpecificTestsArgumentProcessorCapabilities capabilities = new(); Assert.AreEqual("/Tests", capabilities.CommandName); - StringAssert.Contains(capabilities.HelpContentResourceName.NormalizeLineEndings(), - "/Tests:\r\n Run tests with names that match the provided values.".NormalizeLineEndings()); + Assert.Contains("/Tests:\r\n Run tests with names that match the provided values.".NormalizeLineEndings(), + capabilities.HelpContentResourceName.NormalizeLineEndings()); Assert.AreEqual(HelpContentPriority.RunSpecificTestsArgumentProcessorHelpPriority, capabilities.HelpPriority); Assert.IsTrue(capabilities.IsAction); diff --git a/test/vstest.console.UnitTests/Processors/TestAdapterLoadingStrategyArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/TestAdapterLoadingStrategyArgumentProcessorTests.cs index f60d0ffb8d..4d18ead876 100644 --- a/test/vstest.console.UnitTests/Processors/TestAdapterLoadingStrategyArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/TestAdapterLoadingStrategyArgumentProcessorTests.cs @@ -73,19 +73,8 @@ public void InitializeShouldAddRightAdapterPathInErrorMessage() var message = "The path 'd:\\users' specified in the 'TestAdapterPath' is invalid. Error: The custom test adapter search path provided was not found, provide a valid path and try again."; - var isExceptionThrown = false; - try - { - executor.Initialize(nameof(TestAdapterLoadingStrategy.Default)); - } - catch (Exception ex) - { - isExceptionThrown = true; - Assert.IsTrue(ex is CommandLineException); - Assert.AreEqual(message, ex.Message); - } - - Assert.IsTrue(isExceptionThrown); + var ex = Assert.ThrowsExactly(() => executor.Initialize(nameof(TestAdapterLoadingStrategy.Default))); + Assert.AreEqual(message, ex.Message); } @@ -104,19 +93,7 @@ public void InitializeShouldThrowIfPathDoesNotExist() var message = $"The path '{folder}' specified in the 'TestAdapterPath' is invalid. Error: The custom test adapter search path provided was not found, provide a valid path and try again."; - var isExceptionThrown = false; - - try - { - executor.Initialize(nameof(TestAdapterLoadingStrategy.Default)); - } - catch (Exception ex) - { - isExceptionThrown = true; - Assert.IsTrue(ex is CommandLineException); - Assert.AreEqual(message, ex.Message); - } - - Assert.IsTrue(isExceptionThrown); + var ex2 = Assert.ThrowsExactly(() => executor.Initialize(nameof(TestAdapterLoadingStrategy.Default))); + Assert.AreEqual(message, ex2.Message); } } diff --git a/test/vstest.console.UnitTests/Processors/TestAdapterPathArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/TestAdapterPathArgumentProcessorTests.cs index 8dd96a60ad..20ffa9c4e0 100644 --- a/test/vstest.console.UnitTests/Processors/TestAdapterPathArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/TestAdapterPathArgumentProcessorTests.cs @@ -83,20 +83,8 @@ public void InitializeShouldThrowIfArgumentIsNull() var message = @"The /TestAdapterPath parameter requires a value, which is path of a location containing custom test adapters. Example: /TestAdapterPath:c:\MyCustomAdapters"; - var isExceptionThrown = false; - - try - { - executor.Initialize(null); - } - catch (Exception ex) - { - isExceptionThrown = true; - Assert.IsTrue(ex is CommandLineException); - Assert.AreEqual(message, ex.Message); - } - - Assert.IsTrue(isExceptionThrown); + var ex = Assert.ThrowsExactly(() => executor.Initialize(null)); + Assert.AreEqual(message, ex.Message); } [TestMethod] @@ -109,20 +97,8 @@ public void InitializeShouldThrowIfArgumentIsAWhiteSpace() var message = @"The /TestAdapterPath parameter requires a value, which is path of a location containing custom test adapters. Example: /TestAdapterPath:c:\MyCustomAdapters"; - var isExceptionThrown = false; - - try - { - executor.Initialize(" "); - } - catch (Exception ex) - { - isExceptionThrown = true; - Assert.IsTrue(ex is CommandLineException); - Assert.AreEqual(message, ex.Message); - } - - Assert.IsTrue(isExceptionThrown); + var ex2 = Assert.ThrowsExactly(() => executor.Initialize(" ")); + Assert.AreEqual(message, ex2.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/TestCaseFilterArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/TestCaseFilterArgumentProcessorTests.cs index f16d22e52c..52231ae264 100644 --- a/test/vstest.console.UnitTests/Processors/TestCaseFilterArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/TestCaseFilterArgumentProcessorTests.cs @@ -32,7 +32,7 @@ public void CapabilitiesShouldAppropriateProperties() { TestCaseFilterArgumentProcessorCapabilities capabilities = new(); Assert.AreEqual("/TestCaseFilter", capabilities.CommandName); - StringAssert.Contains(capabilities.HelpContentResourceName, "/TestCaseFilter:" + Environment.NewLine + " Run tests that match the given expression." + Environment.NewLine + " is of the format Operator[|&]"); + Assert.Contains("/TestCaseFilter:" + Environment.NewLine + " Run tests that match the given expression." + Environment.NewLine + " is of the format Operator[|&]", capabilities.HelpContentResourceName); Assert.AreEqual(HelpContentPriority.TestCaseFilterArgumentProcessorHelpPriority, capabilities.HelpPriority); Assert.IsFalse(capabilities.IsAction); @@ -51,15 +51,8 @@ public void ExecutorInitializeWithNullOrEmptyTestCaseFilterShouldThrowCommandLin var options = CommandLineOptions.Instance; TestCaseFilterArgumentExecutor executor = new(options); - try - { - executor.Initialize(null); - } - catch (Exception ex) - { - Assert.IsTrue(ex is CommandLineException); - StringAssert.Contains(ex.Message, @"The /TestCaseFilter argument requires the filter value."); - } + var ex = Assert.ThrowsExactly(() => executor.Initialize(null)); + Assert.Contains(@"The /TestCaseFilter argument requires the filter value.", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/TestSourceArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/TestSourceArgumentProcessorTests.cs index 9f4533c153..e75b58aa40 100644 --- a/test/vstest.console.UnitTests/Processors/TestSourceArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/TestSourceArgumentProcessorTests.cs @@ -74,16 +74,9 @@ public void ExecuterInitializeWithInvalidSourceShouldThrowCommandLineException() // This path is invalid string testFilePath = "TestFile.txt"; - try - { - executor.Initialize(testFilePath); - } - catch (Exception ex) - { - Assert.IsTrue(ex is TestSourceException); - StringAssert.StartsWith(ex.Message, "The test source file \""); - StringAssert.EndsWith(ex.Message, testFilePath + "\" provided was not found."); - } + var ex = Assert.ThrowsExactly(() => executor.Initialize(testFilePath)); + Assert.StartsWith("The test source file \"", ex.Message); + Assert.EndsWith(testFilePath + "\" provided was not found.", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs index f493f7a6e5..48f971b4a3 100644 --- a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs +++ b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs @@ -70,11 +70,8 @@ public void CreateArgumentProcessorShouldReturnThrowExceptionIfArgumentsIsNull() var command = "--"; ArgumentProcessorFactory factory = ArgumentProcessorFactory.Create(); - Action action = () => factory.CreateArgumentProcessor(command, null!); - - ExceptionUtilities.ThrowsException( - action, - "Cannot be null or empty", "argument"); + var ex = Assert.ThrowsExactly(() => factory.CreateArgumentProcessor(command, null!)); + Assert.Contains("Cannot be null or empty", ex.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs index a597af523d..5edc10c0c7 100644 --- a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs +++ b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs @@ -15,19 +15,13 @@ public class ArgumentProcessorUtilitiesTests { [TestMethod] [DataRow("")] - [DataRow(" ")] [DataRow(";;;;")] public void GetArgumentListShouldThrowErrorOnInvalidArgument(string argument) { - try - { - ArgumentProcessorUtilities.GetArgumentList(argument, ArgumentProcessorUtilities.SemiColonArgumentSeparator, "test exception."); - } - catch (Exception e) - { - Assert.IsTrue(e.GetType().Equals(typeof(CommandLineException))); - Assert.IsTrue(e.Message.Contains("test exception.")); - } + var e = Assert.ThrowsExactly(() => + ArgumentProcessorUtilities.GetArgumentList(argument, ArgumentProcessorUtilities.SemiColonArgumentSeparator, "test exception.")); + Assert.IsInstanceOfType(e); + Assert.Contains("test exception.", e.Message); } [TestMethod] @@ -43,15 +37,10 @@ public void GetArgumentListShouldReturnCorrectArgumentList(string argument) [DataRow(["key1=value1", "invalidPair", "key2=value2"])] public void GetArgumentParametersShouldThrowErrorOnInvalidParameters(string[] parameterArgs) { - try - { - ArgumentProcessorUtilities.GetArgumentParameters(parameterArgs, ArgumentProcessorUtilities.EqualNameValueSeparator, "test exception."); - } - catch (Exception e) - { - Assert.IsTrue(e.GetType().Equals(typeof(CommandLineException))); - Assert.IsTrue(e.Message.Contains("test exception.")); - } + var e = Assert.ThrowsExactly(() => + ArgumentProcessorUtilities.GetArgumentParameters(parameterArgs, ArgumentProcessorUtilities.EqualNameValueSeparator, "test exception.")); + Assert.IsInstanceOfType(e); + Assert.Contains("test exception.", e.Message); } [TestMethod] diff --git a/test/vstest.console.UnitTests/TestPlatformHelpers/TestRequestManagerTests.cs b/test/vstest.console.UnitTests/TestPlatformHelpers/TestRequestManagerTests.cs index 408171f492..12c4429d23 100644 --- a/test/vstest.console.UnitTests/TestPlatformHelpers/TestRequestManagerTests.cs +++ b/test/vstest.console.UnitTests/TestPlatformHelpers/TestRequestManagerTests.cs @@ -45,6 +45,8 @@ namespace vstest.console.UnitTests.TestPlatformHelpers; [TestClass] public class TestRequestManagerTests { + public TestContext TestContext { get; set; } = null!; + private DummyLoggerEvents _mockLoggerEvents; private readonly CommandLineOptions _commandLineOptions; private readonly Mock _mockTestPlatform; @@ -331,7 +333,7 @@ public void DiscoverTestsShouldCollectMetrics() Assert.AreEqual("Other", targetDevice); Assert.AreEqual(2, maxcount); Assert.AreEqual("X86", targetPlatform.ToString()); - Assert.AreEqual(true, disableAppDomain); + Assert.IsTrue((bool)disableAppDomain); } [TestMethod] @@ -519,11 +521,11 @@ public void DiscoverTestsShouldCollectCommands() var commandLineArray = commandLineSwitches.ToString(); - Assert.IsTrue(commandLineArray!.Contains("/Parallel")); - Assert.IsTrue(commandLineArray.Contains("/EnableCodeCoverage")); - Assert.IsTrue(commandLineArray.Contains("/InIsolation")); - Assert.IsTrue(commandLineArray.Contains("/UseVsixExtensions")); - Assert.IsTrue(commandLineArray.Contains("/settings//.RunSettings")); + Assert.Contains("/Parallel", commandLineArray!); + Assert.Contains("/EnableCodeCoverage", commandLineArray!); + Assert.Contains("/InIsolation", commandLineArray!); + Assert.Contains("/UseVsixExtensions", commandLineArray!); + Assert.Contains("/settings//.RunSettings", commandLineArray!); } [TestMethod] @@ -571,7 +573,7 @@ public void DiscoverTestsShouldCollectTestSettings() Assert.IsTrue(actualRequestData!.MetricsCollection.Metrics.TryGetValue(TelemetryDataConstants.CommandLineSwitches, out var commandLineSwitches)); var commandLineArray = commandLineSwitches.ToString(); - Assert.IsTrue(commandLineArray!.Contains("/settings//.TestSettings")); + Assert.Contains("/settings//.TestSettings", commandLineArray!); } [TestMethod] @@ -619,7 +621,7 @@ public void DiscoverTestsShouldCollectVsmdiFile() Assert.IsTrue(actualRequestData!.MetricsCollection.Metrics.TryGetValue(TelemetryDataConstants.CommandLineSwitches, out var commandLineSwitches)); var commandLineArray = commandLineSwitches.ToString(); - Assert.IsTrue(commandLineArray!.Contains("/settings//.vsmdi")); + Assert.Contains("/settings//.vsmdi", commandLineArray!); } [TestMethod] @@ -667,7 +669,7 @@ public void DiscoverTestsShouldCollectTestRunConfigFile() Assert.IsTrue(actualRequestData!.MetricsCollection.Metrics.TryGetValue(TelemetryDataConstants.CommandLineSwitches, out var commandLineSwitches)); var commandLineArray = commandLineSwitches.ToString(); - Assert.IsTrue(commandLineArray!.Contains("/settings//.testrunConfig")); + Assert.Contains("/settings//.testrunConfig", commandLineArray!); } [TestMethod] @@ -698,8 +700,8 @@ public void DiscoverTestsShouldUpdateFrameworkAndPlatformIfNotSpecifiedInDesignM _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny())); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny())); - Assert.IsTrue(actualDiscoveryCriteria!.RunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(actualDiscoveryCriteria.RunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, actualDiscoveryCriteria!.RunSettings!); + Assert.Contains(nameof(Architecture.ARM), actualDiscoveryCriteria.RunSettings!); } [TestMethod] @@ -732,8 +734,8 @@ public void DiscoverTestsShouldNotUpdateFrameworkAndPlatformIfSpecifiedInDesignM _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny()), Times.Never); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny()), Times.Never); - Assert.IsTrue(actualDiscoveryCriteria!.RunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(actualDiscoveryCriteria.RunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, actualDiscoveryCriteria!.RunSettings!); + Assert.Contains(nameof(Architecture.ARM), actualDiscoveryCriteria.RunSettings!); } [TestMethod] @@ -763,8 +765,8 @@ public void DiscoverTestsShouldUpdateFrameworkAndPlatformInCommandLineScenariosI _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny())); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny())); - Assert.IsTrue(actualDiscoveryCriteria!.RunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(actualDiscoveryCriteria.RunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, actualDiscoveryCriteria!.RunSettings!); + Assert.Contains(nameof(Architecture.ARM), actualDiscoveryCriteria.RunSettings!); } [TestMethod] @@ -804,8 +806,8 @@ public void DiscoverTestsShouldNotInferAndUpdateFrameworkAndPlatformInCommandLin _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny()), Times.Once); // but we don't update the settings, to keep what user specified - Assert.IsFalse(actualDiscoveryCriteria!.RunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsFalse(actualDiscoveryCriteria.RunSettings.Contains(nameof(Architecture.ARM))); + Assert.DoesNotContain(Constants.DotNetFramework46, actualDiscoveryCriteria!.RunSettings!); + Assert.DoesNotContain(nameof(Architecture.ARM), actualDiscoveryCriteria.RunSettings!); } [TestMethod] @@ -976,11 +978,11 @@ public void RunTestsShouldCollectCommands() var commandLineArray = commandLineSwitches.ToString(); - Assert.IsTrue(commandLineArray!.Contains("/Parallel")); - Assert.IsTrue(commandLineArray.Contains("/EnableCodeCoverage")); - Assert.IsTrue(commandLineArray.Contains("/InIsolation")); - Assert.IsTrue(commandLineArray.Contains("/UseVsixExtensions")); - Assert.IsTrue(commandLineArray.Contains("/settings//.RunSettings")); + Assert.Contains("/Parallel", commandLineArray!); + Assert.Contains("/EnableCodeCoverage", commandLineArray!); + Assert.Contains("/InIsolation", commandLineArray!); + Assert.Contains("/UseVsixExtensions", commandLineArray!); + Assert.Contains("/settings//.RunSettings", commandLineArray!); } [TestMethod] @@ -1135,7 +1137,7 @@ public void RunTestsShouldCollectMetrics() Assert.AreEqual("Other", targetDevice); Assert.AreEqual(2, maxcount); Assert.AreEqual("X86", targetPlatform.ToString()); - Assert.AreEqual(true, disableAppDomain); + Assert.IsTrue((bool)disableAppDomain); } [TestMethod] @@ -1249,10 +1251,10 @@ public void RunTestsMultipleCallsShouldNotRunInParallel() }); var mockCustomlauncher = new Mock(); - var task1 = Task.Run(() => _testRequestManager.RunTests(payload1, mockCustomlauncher.Object, mockRunEventsRegistrar1.Object, _protocolConfig)); - var task2 = Task.Run(() => _testRequestManager.RunTests(payload2, mockCustomlauncher.Object, mockRunEventsRegistrar2.Object, _protocolConfig)); + var task1 = Task.Run(() => _testRequestManager.RunTests(payload1, mockCustomlauncher.Object, mockRunEventsRegistrar1.Object, _protocolConfig), TestContext.CancellationToken); + var task2 = Task.Run(() => _testRequestManager.RunTests(payload2, mockCustomlauncher.Object, mockRunEventsRegistrar2.Object, _protocolConfig), TestContext.CancellationToken); - Task.WaitAll(task1, task2); + Task.WaitAll([task1, task2], TestContext.CancellationToken); if (run1Start < run2Start) { @@ -1433,8 +1435,8 @@ public void RunTestsShouldShouldUpdateFrameworkAndPlatformIfNotSpecifiedInDesign _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny())); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny())); - Assert.IsTrue(actualTestRunCriteria!.TestRunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(actualTestRunCriteria.TestRunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, actualTestRunCriteria!.TestRunSettings!); + Assert.Contains(nameof(Architecture.ARM), actualTestRunCriteria.TestRunSettings!); } @@ -1472,8 +1474,8 @@ public void RunTestsShouldNotUpdateFrameworkAndPlatformIfSpecifiedInDesignMode() _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny()), Times.Once); // but don't update runsettings because we want to keep what user specified - Assert.IsTrue(actualTestRunCriteria!.TestRunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(actualTestRunCriteria!.TestRunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, actualTestRunCriteria!.TestRunSettings!); + Assert.Contains(nameof(Architecture.ARM), actualTestRunCriteria!.TestRunSettings!); } [TestMethod] @@ -1513,7 +1515,7 @@ public void RunTestsShouldNotUpdatePlatformIfSpecifiedInDesignMode(string target _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny()), Times.Once); // don't update it in runsettings to keep what user provided - Assert.IsTrue(actualTestRunCriteria!.TestRunSettings!.Contains(targetPlatform)); + Assert.Contains(targetPlatform, actualTestRunCriteria!.TestRunSettings!); } [TestMethod] @@ -1545,8 +1547,8 @@ public void RunTestsShouldUpdateFrameworkAndPlatformInCommandLineScenarios() _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny())); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny())); - Assert.IsTrue(actualTestRunCriteria!.TestRunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(actualTestRunCriteria.TestRunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, actualTestRunCriteria!.TestRunSettings!); + Assert.Contains(nameof(Architecture.ARM), actualTestRunCriteria.TestRunSettings!); } [TestMethod] @@ -1585,8 +1587,8 @@ public void RunTestsShouldNotpdateFrameworkAndPlatformInRunsettingsIfSpecifiedBy _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny()), Times.Once); // but don't update them in runsettings so we keep what user specified - Assert.IsFalse(actualTestRunCriteria!.TestRunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsFalse(actualTestRunCriteria.TestRunSettings.Contains(nameof(Architecture.ARM))); + Assert.DoesNotContain(Constants.DotNetFramework46, actualTestRunCriteria!.TestRunSettings!); + Assert.DoesNotContain(nameof(Architecture.ARM), actualTestRunCriteria.TestRunSettings!); } [TestMethod] @@ -1626,8 +1628,8 @@ public void RunTestsWithTestCasesShouldUpdateFrameworkAndPlatformIfNotSpecifiedI _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny())); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny())); - Assert.IsTrue(actualTestRunCriteria!.TestRunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(actualTestRunCriteria.TestRunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, actualTestRunCriteria!.TestRunSettings!); + Assert.Contains(nameof(Architecture.ARM), actualTestRunCriteria.TestRunSettings!); CollectionAssert.AreEqual(actualSources, archSources); CollectionAssert.AreEqual(actualSources, fxSources); } @@ -1657,19 +1659,10 @@ public void RunTestShouldThrowExceptionIfRunSettingWithDcHasTestSettingsInIt() }; _commandLineOptions.EnableCodeCoverage = false; - bool exceptionThrown = false; - try - { - _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); - } - catch (SettingsException ex) - { - exceptionThrown = true; - Assert.IsTrue(ex.Message.Contains(@"C:\temp.testsettings"), ex.Message); - } - - Assert.IsTrue(exceptionThrown, "Initialize should throw exception"); + var ex = Assert.ThrowsExactly(() => + _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig)); + Assert.Contains(@"C:\temp.testsettings", ex.Message); } [TestMethod] @@ -1697,19 +1690,10 @@ public void RunTestShouldThrowExceptionIfRunSettingWithDcHasTestSettingsAndEnabl }; _commandLineOptions.EnableCodeCoverage = true; - bool exceptionThrown = false; - try - { - _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); - } - catch (SettingsException ex) - { - exceptionThrown = true; - Assert.IsTrue(ex.Message.Contains(@"C:\temp.testsettings"), ex.Message); - } - - Assert.IsTrue(exceptionThrown, "Initialize should throw exception"); + var ex = Assert.ThrowsExactly(() => + _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig)); + Assert.Contains(@"C:\temp.testsettings", ex.Message); } [TestMethod] @@ -1759,7 +1743,7 @@ public void RunTestsShouldAddConsoleLoggerInRunSettingsInNonDesignMode() _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings)!.LoggerSettingsList; - Assert.AreEqual(1, loggerSettingsList.Count); + Assert.HasCount(1, loggerSettingsList); Assert.AreEqual("Console", loggerSettingsList[0].FriendlyName); Assert.IsNotNull(loggerSettingsList[0].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[0].CodeBase); @@ -1797,7 +1781,7 @@ public void RunTestsShouldAddConsoleLoggerInRunSettingsIfDesignModeSetFalseInRun _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings)!.LoggerSettingsList; - Assert.AreEqual(2, loggerSettingsList.Count); + Assert.HasCount(2, loggerSettingsList); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("Console", loggerSettingsList[1].FriendlyName); @@ -1840,7 +1824,7 @@ public void DiscoverTestsShouldAddConsoleLoggerInRunSettingsIfDesignModeSetFalse new Mock().Object, _protocolConfig); var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings)!.LoggerSettingsList; - Assert.AreEqual(2, loggerSettingsList.Count); + Assert.HasCount(2, loggerSettingsList); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("Console", loggerSettingsList[1].FriendlyName); @@ -1870,7 +1854,7 @@ public void RunTestsShouldNotAddConsoleLoggerInRunSettingsInDesignMode() (IRequestData requestData, TestRunCriteria runCriteria, TestPlatformOptions options, Dictionary sourceToSourceDetailMap, IWarningLogger _) => actualTestRunCriteria = runCriteria).Returns(mockTestRunRequest.Object); _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); - Assert.IsFalse(actualTestRunCriteria!.TestRunSettings!.Contains("LoggerRunSettings")); + Assert.DoesNotContain("LoggerRunSettings", actualTestRunCriteria!.TestRunSettings!); } [TestMethod] @@ -1898,7 +1882,7 @@ public void DiscoverTestsShouldAddConsoleLoggerInRunSettingsInNonDesignMode() new Mock().Object, _protocolConfig); var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings)!.LoggerSettingsList; - Assert.AreEqual(1, loggerSettingsList.Count); + Assert.HasCount(1, loggerSettingsList); Assert.AreEqual("Console", loggerSettingsList[0].FriendlyName); Assert.IsNotNull(loggerSettingsList[0].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[0].CodeBase); @@ -1929,7 +1913,7 @@ public void DiscoverTestsShouldNotAddConsoleLoggerInRunSettingsInDesignMode() _testRequestManager.DiscoverTests(payload, new Mock().Object, _protocolConfig); - Assert.IsFalse(actualDiscoveryCriteria!.RunSettings!.Contains("LoggerRunSettings")); + Assert.DoesNotContain("LoggerRunSettings", actualDiscoveryCriteria!.RunSettings!); } [TestMethod] @@ -1969,14 +1953,14 @@ public void RunTestsShouldOverrideOnlyAssemblyNameIfConsoleLoggerAlreadyPresentI _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings)!.LoggerSettingsList; - Assert.AreEqual(2, loggerSettingsList.Count); + Assert.HasCount(2, loggerSettingsList); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("console", loggerSettingsList[1].FriendlyName); Assert.AreEqual(new Uri("logger://tempconsoleUri").ToString(), loggerSettingsList[1].Uri!.ToString()); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].AssemblyQualifiedName); Assert.AreNotEqual("tempCodeBase", loggerSettingsList[1].CodeBase); - Assert.IsTrue(loggerSettingsList[1].Configuration!.InnerXml.Contains("Value1")); + Assert.Contains("Value1", loggerSettingsList[1].Configuration!.InnerXml); Assert.IsNotNull(loggerSettingsList[1].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[1].CodeBase); } @@ -2021,14 +2005,14 @@ public void DiscoverTestsShouldOverrideOnlyAssemblyNameIfConsoleLoggerAlreadyPre new Mock().Object, _protocolConfig); var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings)!.LoggerSettingsList; - Assert.AreEqual(2, loggerSettingsList.Count); + Assert.HasCount(2, loggerSettingsList); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("consoleTemp", loggerSettingsList[1].FriendlyName); Assert.AreEqual(new Uri("logger://Microsoft/TestPlatform/ConsoleLogger/v1").ToString(), loggerSettingsList[1].Uri!.ToString()); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].AssemblyQualifiedName); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].CodeBase); - Assert.IsTrue(loggerSettingsList[1].Configuration!.InnerXml.Contains("Value1")); + Assert.Contains("Value1", loggerSettingsList[1].Configuration!.InnerXml); Assert.IsNotNull(loggerSettingsList[1].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[1].CodeBase); } @@ -2070,14 +2054,14 @@ public void RunTestsShouldOverrideOnlyAssemblyNameIfConsoleLoggerAlreadyPresentI _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings)!.LoggerSettingsList; - Assert.AreEqual(2, loggerSettingsList.Count); + Assert.HasCount(2, loggerSettingsList); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("console", loggerSettingsList[1].FriendlyName); Assert.AreEqual(new Uri("logger://tempconsoleUri").ToString(), loggerSettingsList[1].Uri!.ToString()); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].AssemblyQualifiedName); Assert.AreNotEqual("tempCodeBase", loggerSettingsList[1].CodeBase); - Assert.IsTrue(loggerSettingsList[1].Configuration!.InnerXml.Contains("Value1")); + Assert.Contains("Value1", loggerSettingsList[1].Configuration!.InnerXml); Assert.IsNotNull(loggerSettingsList[1].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[1].CodeBase); } @@ -2122,14 +2106,14 @@ public void DiscoverTestsShouldOverrideOnlyAssemblyNameIfConsoleLoggerAlreadyPre new Mock().Object, _protocolConfig); var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings)!.LoggerSettingsList; - Assert.AreEqual(2, loggerSettingsList.Count); + Assert.HasCount(2, loggerSettingsList); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("consoleTemp", loggerSettingsList[1].FriendlyName); Assert.AreEqual(new Uri("logger://Microsoft/TestPlatform/ConsoleLogger/v1").ToString(), loggerSettingsList[1].Uri!.ToString()); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].AssemblyQualifiedName); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].CodeBase); - Assert.IsTrue(loggerSettingsList[1].Configuration!.InnerXml.Contains("Value1")); + Assert.Contains("Value1", loggerSettingsList[1].Configuration!.InnerXml); Assert.IsNotNull(loggerSettingsList[1].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[1].CodeBase); } @@ -2205,7 +2189,9 @@ public async Task CancelTestRunAttachmentsProcessingShouldSucceedIfRequestInProg { i++; Console.WriteLine($"Iteration {i}"); +#pragma warning disable MSTEST0049 // Intentionally not using CancellationToken - the mock must poll without throwing Task.Delay(5).Wait(); +#pragma warning restore MSTEST0049 } r.MetricsCollection.Add(TelemetryDataConstants.AttachmentsProcessingState, "Canceled"); @@ -2219,8 +2205,8 @@ public async Task CancelTestRunAttachmentsProcessingShouldSucceedIfRequestInProg CollectMetrics = true }; - Task task = Task.Run(() => _testRequestManager.ProcessTestRunAttachments(payload, mockEventsHandler.Object, _protocolConfig)); - await Task.Delay(50); + Task task = Task.Run(() => _testRequestManager.ProcessTestRunAttachments(payload, mockEventsHandler.Object, _protocolConfig), TestContext.CancellationToken); + await Task.Delay(50, TestContext.CancellationToken); _testRequestManager.CancelTestRunAttachmentsProcessing(); await task; @@ -2303,8 +2289,8 @@ public void StartTestSessionShouldUpdateSettings() .Callback( (IRequestData _, StartTestSessionCriteria criteria, ITestSessionEventsHandler _, Dictionary _, IWarningLogger _) => { - Assert.IsTrue(criteria.RunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(criteria.RunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, criteria.RunSettings!); + Assert.Contains(nameof(Architecture.ARM), criteria.RunSettings!); }); _testRequestManager.StartTestSession( @@ -2352,8 +2338,8 @@ public void StartTestSessionShouldSendCompletedEventIfTestPlatformReturnsFalse() .Callback( (IRequestData _, StartTestSessionCriteria criteria, ITestSessionEventsHandler _, Dictionary _, IWarningLogger _) => { - Assert.IsTrue(criteria.RunSettings!.Contains(Constants.DotNetFramework46)); - Assert.IsTrue(criteria.RunSettings.Contains(nameof(Architecture.ARM))); + Assert.Contains(Constants.DotNetFramework46, criteria.RunSettings!); + Assert.Contains(nameof(Architecture.ARM), criteria.RunSettings!); }); _testRequestManager.StartTestSession( @@ -2392,23 +2378,14 @@ public void StartTestSessionShouldThrowSettingsExceptionWhenFindingIncompatibleD }; _commandLineOptions.EnableCodeCoverage = false; - bool exceptionThrown = false; - try - { + var ex = Assert.ThrowsExactly(() => _testRequestManager.StartTestSession( payload, new Mock().Object, new Mock().Object, - _protocolConfig); - } - catch (SettingsException ex) - { - exceptionThrown = true; - Assert.IsTrue(ex.Message.Contains(@"C:\temp.testsettings"), ex.Message); - } - - Assert.IsTrue(exceptionThrown, "Initialize should throw exception"); + _protocolConfig)); + Assert.Contains(@"C:\temp.testsettings", ex.Message); } [TestMethod] @@ -2561,7 +2538,7 @@ public void StopTestSessionShouldPropagateExceptionWhenKillSessionThrows() Assert.IsNotNull(eventArgs.TestSessionInfo); Assert.IsNotNull(eventArgs.Metrics); Assert.AreEqual(eventArgs.TestSessionInfo, testSessionInfo); - Assert.AreEqual(false, eventArgs.IsStopped); + Assert.IsFalse(eventArgs.IsStopped); }); Assert.ThrowsExactly(() => @@ -2698,7 +2675,7 @@ public void UpdateCodeCoverageSettings_SetEnableDynamicNativeInstrumentationToFa // Assert Assert.IsTrue(result); - StringAssert.Contains(xmlDocument.OuterXml, "FalseFalse"); + Assert.Contains("FalseFalse", xmlDocument.OuterXml); } [TestMethod] @@ -2724,7 +2701,7 @@ public void UpdateCodeCoverageSettings_SetEnableDynamicNativeInstrumentationToFa // Assert Assert.IsTrue(result); - StringAssert.Contains(xmlDocument.OuterXml, $"False"); + Assert.Contains($"False", xmlDocument.OuterXml); } [TestMethod] @@ -2762,7 +2739,7 @@ public void UpdateCodeCoverageSettings_DontSetEnableDynamicNativeInstrumentation // Assert // No matter what user has set, we don't override it. Assert.IsFalse(result); - StringAssert.Contains(xmlDocument.OuterXml, $"{setting}"); + Assert.Contains($"{setting}", xmlDocument.OuterXml); } [TestMethod] @@ -2801,7 +2778,7 @@ public void UpdateCodeCoverageSettings_SetEnableDynamicNativeInstrumentationToFa // Assert Assert.IsTrue(result); - StringAssert.Contains(xmlDocument.OuterXml, $"False"); + Assert.Contains($"False", xmlDocument.OuterXml); } private static DiscoveryRequestPayload CreateDiscoveryPayload(string runsettings)